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

自作多情 提交于 2020-02-02 02:21:29

问题


I have a template class, something like:

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

Now, I would like to change Seconds to be a duration, so the class can be parametrized with std::chrono::duration. For example, I'd like to be able to do this:

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

Also, in the template, I'd like to specify a default value, something like std::chrono::seconds(30).


回答1:


You can design your template in a clever way:

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

And then you can instantiate your template as

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

Or, actually having these values as defaults, simply

MyClass < std::string > object;

Edit:

Taking into account PaperBirdMaster's request, you can limit template's Duration type, to be std::chrono::duration only, this way:

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


来源:https://stackoverflow.com/questions/28875853/how-can-i-use-stdchronoduration-as-a-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!