检测编译时是否存在默认构造函数 [英] Detect if a default constructor exists at compile time
问题描述
我想检查一个默认的构造函数是否存在一个模板参数。
我想这样做:
I'm trying to check if a default constructor exists for a template argument. I want to do something like this:
template <typename A>
class Blah
{
Blah() { A* = new A(); }
}
但我想在编译时检测到 SFINAE 或一些其他的技巧,如果构造函数存在,并提出一个 static_assert
我自己的,如果没有。
But i want to detect at compile time via SFINAE or some other trick if that constructor exists, and raise a static_assert
of my own if it doesn't.
当我有类( std :: vector
)没有一个默认构造函数,但是一个构造函数与默认参数的问题出现。
The problem arises when i have classes (like std::vector
) that dont have a "default constructor" but a constructor with default parameters.
因此,使用 std :: has_trivial_default_constructor
将不会返回true。虽然我可以使用新向量< T>()
。
So using std::has_trivial_default_constructor
won't return true. Although i can use new vector<T>()
.
推荐答案
这里是类型trait的一个可能的实现:
Here's a possible implementation of the type trait:
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
}
这篇关于检测编译时是否存在默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!