Yoc*_*mer 1 c++ templates constructor sfinae
我正在尝试检查模板参数是否存在默认构造函数.我想做这样的事情:
template <typename A>
class Blah
{
Blah() { A* = new A(); }
}
Run Code Online (Sandbox Code Playgroud)
但是我希望在编译时通过SFINAE或其他技巧检测,如果该构造函数存在,并且static_assert如果不存在则引发我自己的.
当我有类(没有std::vector)没有"默认构造函数"但是具有默认参数的构造函数时,问题就出现了.
所以使用std::has_trivial_default_constructor不会返回true.虽然我可以使用new vector<T>().
这是类型特征的可能实现:
template<typename T>
class is_default_constructible {
typedef char yes;
typedef struct { char arr[2]; } no;
template<typename U>
static decltype(U(), yes()) test(int);
template<typename>
static no test(...);
public:
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
struct foo {
foo(int) {}
};
int main()
{
std::cout << is_default_constructible<foo>::value << '\n' // 0
<< is_default_constructible<std::vector<int>>::value; // 1
}
Run Code Online (Sandbox Code Playgroud)