如何使用std :: chrono :: duration作为模板参数?

时间:2015-03-05 10:40:20

标签: c++ templates c++11 stl chrono

我有一个模板类,如:

template < typename T, size_t Seconds > class MyClass {}

现在,我想将Seconds更改为持续时间,因此可以使用std::chrono::duration对类进行参数化。例如,我希望能够这样做:

MyClass < std::string, std::chrono::seconds(30) > object;

此外,在模板中,我想指定一个默认值,例如std::chrono::seconds(30)

1 个答案:

答案 0 :(得分:11)

您可以巧妙地设计模板:

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,这样:

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, typename Duration = std::chrono::seconds, 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, std::chrono::seconds, 1> obj1;       // Ok
    MyClass < std::string, std::chrono::milliseconds, 1> obj2;  // Ok
    MyClass < std::string, int, 1> obj3;                        // Error
    return 0;
}