c++ - 选择类构造器

标签 c++ templates

我想让类模板构造函数默认如果它是微不足道的并且是T的默认值,就像这样:

template <typename T>
class my_class {
public:
    template <typename <std::enable_if<std::is_trivially_default_constructible<T>::value, int>::type = 0>
    constexpr my_class() = default;

    template <typename <std::enable_if<!std::is_trivially_default_constructible<T>::value, int>::type = 0>
    constexpr my_class() {};
}

当然,此代码不起作用(如果条件不满足,则为空参数)。怎么做?

最佳答案

您可以为 T 何时是和不是普通的默认构造提供单独的特化:

template <typename T, bool = std::is_trivially_default_constructible<T>::value>
class my_class {
public:
    constexpr my_class() = default;
};

template <typename T>
class my_class<T, false> {
public:
    constexpr my_class() {};  
};

关于c++ - 选择类构造器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39827411/

相关文章:

c++ - QStackedWidget 从第 1 页导航到第 2 页

c++ - ISO C 或 C++ 标准是否指定 `const char *` 应该是 NULL 终止的字符串?

c++ - 应该接受不同输入参数的纯虚函数——应该如何实现?

c++ - 在允许用作模板类型的函数内使用内联类吗?

php - symfony2.1 : count doctrine collection in twig template

c++ - Linux C++ 上 Gtkmm 中的 OpenGL 模板缓冲区

c++ - 如何在 std::map 中使用结构作为键

templates - 如何在 ElasticSearch 中正确定义 HashMap

c++ - 模板和类继承

c++ - 将类前向声明​​为模板参数