c++ - 基于参数特征的部分模板特化

标签 c++ template-specialization sfinae

假设我有以下模板:

template <typename T> union example {
    T t;

    constexpr example(const T & t) : t(t) {};

    /* We rely on owning class to take care
     * of destructing the active member */
    ~example() {};
};

因为那里的析构函数,example<T>永远不会被轻易破坏(因此不是文字类型)。我喜欢

这样的部分特化
template <typename T> union
    example<std::enable_if_t<std::is_trivially_destructible<T>::value, T>> {
    T t;

    constexpr example(const T & t) : t(t) {};
};

example<T>T 时可以轻易破坏是,但不幸的是,这给了我(事后看来是合理的)警告

warning: class template partial specialization contains a template parameter that can not be deduced; this partial specialization will never be used

那么有什么办法可以在这里得到我想要的东西吗?

最佳答案

也许有第二个默认模板参数?

#include <type_traits>
#include <iostream>

template <typename T, bool = std::is_trivially_destructible<T>::value>
union example {
    T t;

    constexpr example(const T & t) : t(t) {};

    /* We rely on owning class to take care
     * of destructing the active member */
    ~example() { std::cout << "primary template\n"; }
};

template<typename T>
union example<T, true> {
    T t;

    constexpr example(const T & t) : t(t) {};
};


struct nontrivial
{
    ~nontrivial() { std::cout << "woot!\n"; }
};

int main()
{
    example<nontrivial> e1{{}};
    example<int> e2{{}};
}

关于c++ - 基于参数特征的部分模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22237819/

相关文章:

c++ - 模板特化示例

c++ - 如果 T 是从特定基类派生的,如何专门化模板类的实现

c++ - 为什么这些模板化函数不能不带参数?

c++ - 模板检测 T 是指针还是类

c++ - 从文件中读取数据到C++中的多个数组

c++ - 如何使用 MinGW 编译 C++ std::thread 代码?

Java:使用 char** 和回调作为参数加载 c++ dll

c++ - 来自 WDK 示例的 DbgPrint

c++ - 何时在 C++ 中使用模板<>

c++ - SFINAE 是否依赖于类型推导?