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

标签 c++ templates c++11 stl c++-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)

最佳答案

您可以巧妙地设计模板:

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

关于c++ - 如何使用 std::chrono::duration 作为模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28875853/

相关文章:

c++ - 我可以在 header 中将一个 namespace "import"转换为另一个 namespace 吗?

c++ - 使用 C++ boost 库从图中删除顶点及其所有邻居

c# - 存储集合的最佳实践方式

c++ - 如何在 C++20 模块中使用模板显式实例化?

c++ - 智能指针二维数组作为参数

c++ - 为什么 clang 不产生关于阴影的警告?

c++ - foo 的调用没有匹配函数

c++ - 为具有对象或对象数组作为成员的类运行不同的代码

c++ - std::bind 一个成员函数到 nullptr 处的一个实例导致看似随机的 this 指针

c++ - c++11 及更高版本中 mutex.lock() 和 .unlock() 的确切线程间重新排序约束是什么?