考虑下面的两个模板函数:
template <typename T, typename A>
T* create(A i) {
return new T(i);
}
template <typename T, typename A>
T* create(A i) {
return new T();
}
它们具有相同的签名,但对于给定的 T 和 A 只能实例化一次。
有没有办法将一些 SFINAE 惯用语应用于上述模板函数,以便当且仅当 T 具有接受 A 作为参数类型的构造函数时,可以实例化的模板函数的版本是第一个版本,否则是第二个具有默认构造函数的版本将被实例化,例如:
// S is given, cannot be changed:
struct S {
S(int) {}
}
int main() {
// the first template function should be instantiated since S has S(int)
create<S, int>(0); // the only call in the program
// ...
}
最佳答案
使用is_constructible
:
template <typename T, typename A>
typename std::enable_if<std::is_constructible<T, A>::value, T*>::type create(A i)
{
return new T(i);
}
template <typename T, typename A>
typename std::enable_if<!std::is_constructible<T, A>::value, T*>::type create(A i)
{
return new T();
}
关于c++ - 带构造函数的模板 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283850/