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

How can I use std::chrono::duration as a template parameter?

我有一个模板 class,类似于:

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

现在,我想将 Seconds 更改为持续时间,因此 class 可以用 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,这样:

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;
}