c++ - 带构造函数的模板 SFINAE

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

最佳答案

使用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/

相关文章:

c# - 使用 "strange"函数调用 PInvoke

c++ - 我无法创建虚幻引擎 4 c++ 项目

c++ - 扩展基类并在不更改派生类的情况下使用该功能

c++ - 从森林中构建一棵 n 叉树

c++ - 在 vector 构造函数中从 initializer_list<const char*> 转换为 initializer_list<string>

c++ - pthread_mutex_trylock? Windows 中的线程

c++ - 从非 constexpression 初始化数组

html - 在没有标题栏的情况下在 mfc c++ 中移动窗口?

c++ - ostream_iterator for vector<vector<double>>

c++ - 获取 CAN 比特率