我有一个模板,需要使用以下类型:int
,float
,double
,std::chrono::nanoseconds
,std::chrono::milliseconds
和{{1} }。
该模板具有与std::chrono::seconds
,int
和float
一起使用的成员函数,但我需要为纳秒编写一个专门化,另一个为毫秒,另一个为秒。
要获得一个正常工作的代码,我必须为每个double
“类型”编写一个特殊化代码,并使用基本相同的代码。所以我失去了使用模板的优势。
我已经读过,chrono“types”是持续时间实例化的typedef。
有没有办法只写一个纳秒,毫秒和秒的专业化?
以下是我的代码的样子:
std::chrono
答案 0 :(得分:13)
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()) {}
};
答案 1 :(得分:0)
完整的用法演示发布者:chtz
#include <iostream>
#include <limits>
#include <chrono>
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 ( ) : m_max(std::numeric_limits<T>::max()) {}
};
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()) {}
};
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 namespace std;
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;
}