假设我有以下模板:
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/