我有一个模板类,类似于:
template < typename T,size_t Seconds > class MyClass {}
现在,我想将Seconds更改为持续时间,因此可以使用std :: chrono :: duration对类进行参数化.例如,我希望能够这样做:
MyClass < std::string,std::chrono::seconds(30) > object;
另外,在模板中,我想指定一个默认值,比如std :: chrono :: seconds(30).
解决方法
您可以巧妙地设计模板:
template < typename T,typename Duration = std::chrono::seconds,int duration_value = 30 > class MyClass { // Now you can use duration here: // auto duration = Duration(duration_value); };
然后您可以将模板实例化为
MyClass < std::string,std::chrono::seconds,30 > object;
或者,简单地将这些值作为默认值
MyClass < std::string > object;
编辑:
考虑到PaperBirdMaster的请求,您可以将模板的Duration类型限制为std :: chrono :: duration only,这样:
template <typename T> struct is_chrono_duration { static constexpr bool value = false; }; template <typename Rep,typename Period> struct is_chrono_duration<std::chrono::duration<Rep,Period>> { static constexpr bool value = true; }; template < typename T,int duration_value = 30 > class MyClass { static_assert(is_chrono_duration<Duration>::value,"duration must be a std::chrono::duration"); // Now you can use duration here: // auto duration = Duration(duration_value); }; int main(int argc,char ** argv) { MyClass < std::string,1> obj1; // Ok MyClass < std::string,std::chrono::milliseconds,1> obj2; // Ok MyClass < std::string,int,1> obj3; // Error return 0; }