模板SFINAE与构造函数

时间:2012-07-01 16:46:51

标签: c++ c++11

考虑以下两个模板函数:

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
   // ...
}

1 个答案:

答案 0 :(得分:5)

使用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();
}
相关问题