ClK*_*ClK 10 c++ templates specialization c++11 c++-chrono
我有一个需要下一个类型的工作模板:int
,float
,double
,std::chrono::nanoseconds
,std::chrono::milliseconds
和std::chrono::seconds
.
该模板有一个成员函数一起工作int
,float
和double
但我需要编写纳秒,另一个为毫秒,另一个用于秒一个专业化.
为了得到一个有效的代码,我不得不为每个std::chrono
"类型" 编写一个基本相同代码的专门化.所以我失去了使用模板的优势.
我已经读过计时器"类型"是持续时间实例化的typedef.
有没有办法只写一个纳秒,毫秒和秒的特化?
以下是我的代码的样子:
// file: myclass.hh
template<typename T>
class Myclass {
public:
// Variable (I want to initialize m_max to the maximum value possible for the
// T type)
T m_max ;
// Constructor
Myclass ( ) ;
};
// file: myclass.cc
#include <limits>
#include <chrono>
// Constructor for int, float, double, etc...
template<typename T>
Myclass<T>::Myclass ( ) :
// Here we are setting m_max to the maximum value
m_max( std::numeric_limits<T>::max( ) )
{}
// Constructor: Specialization number 1 for std::chrono::nanoseconds
template<>
Myclass<std::chrono::nanoseconds>::Myclass() :
// Here we are setting m_max to the maximum value
m_max( std::chrono::nanoseconds::max( ) )
{}
// Constructor: Specialization number 2 for std::chrono::milliseconds
template<>
Myclass<std::chrono::milliseconds>::Myclass ( ) :
// Here we are setting m_max to the maximum value
m_max( std::chrono::milliseconds::max() )
{}
// Constructor: Specialization number 3 for std::chrono::seconds
template<>
Myclass<std::chrono::seconds>::Myclass ( ) :
// Here we are setting m_max to the maximum value
m_max( std::chrono::seconds::max( ) )
{}
// Forcing instantiations
template class Myclass<int>;
template class Myclass<float>;
template class Myclass<double>;
template class Myclass<std::chrono::nanoseconds>;
template class Myclass<std::chrono::milliseconds>;
template class Myclass<std::chrono::seconds>;
// file: main.cc
#include <iostream>
int main() {
Myclass<int> intobj;
Myclass<float> floatobj;
Myclass<double> doubleobj;
Myclass<std::chrono::nanoseconds> nanosecondseobj;
Myclass<std::chrono::milliseconds> millisecondseobj;
Myclass<std::chrono::seconds> secondseobj;
using std::cout;
using std::endl;
cout << "Maximum value for int = " << intobj.m_max << endl;
cout << "Maximum value for float = " << floatobj.m_max << endl;
cout << "Maximum value for double = " << doubleobj.m_max << endl;
cout << "Maximum value for nanoseconds = " << nanosecondseobj.m_max.count( ) << endl;
cout << "Maximum value for milliseconds = " << millisecondseobj.m_max.count( ) << endl;
cout << "Maximum value for seconds = " << secondseobj.m_max.count( ) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
cht*_*htz 14
你可以进行部分专业化 std::chrono::duration
template<typename T, typename Ratio>
class Myclass<std::chrono::duration<T,Ratio> > {
public:
// Variable (I want to initialize m_max to the maximum value possible for the
// T type)
std::chrono::duration<T,Ratio> m_max ;
// Constructor
Myclass ( ) : m_max(std::chrono::duration<T,Ratio>::max()) {}
};
Run Code Online (Sandbox Code Playgroud)
用法演示:https: //wandbox.org/permlink/Q8R5pz2UPawnZ1NG
归档时间: |
|
查看次数: |
314 次 |
最近记录: |