我使用SFINAE进行C++ 11中的方法检测,我编写了这个运行示例:
#include <type_traits>
struct Foo
{
Foo();// = delete;
Foo(int);
void my_method();
};
template <typename T, typename ENABLE = void>
struct Detect_My_Method
: std::false_type
{
};
template <typename T>
struct Detect_My_Method<T, decltype(T().my_method())>
: std::true_type
{
};
int main()
{
static_assert(!Detect_My_Method<double>::value, "");
static_assert(Detect_My_Method<Foo>::value, "");
}
如预期般运作。
但是,如果我删除Foo的空构造函数:
struct Foo
{
Foo() = delete;
Foo(int);
void my_method();
};
该示例是不再工作了,我收到以下错误消息:
g++ -std=c++11 declVal.cpp
declVal.cpp: In function ‘int main()’:
declVal.cpp:33:3: error: static assertion failed
static_assert(Detect_My_Method<Foo>::value, "");
问题:的解释以及如何解决?
最佳答案
当空的构造函数被删除时,的构造如下:
decltype(Foo().my_method());
是不再是有效的并且编译器立即抱怨
error: use of deleted function ‘Foo::Foo()’
一种解决方案是使用
std::decval<T>()
因此,替换为:
template <typename T>
struct Detect_My_Method<T, decltype(T().my_method())>
: std::true_type
{
};
通过
template <typename T>
struct Detect_My_Method<T, decltype(std::declval<T>().my_method())>
: std::true_type
{
};
解决了问题。
已学习的类(class):
decltype(Foo().my_method()); // invalid
decltype(std::declval<Foo>().my_method()); // fine
不相等。
关于c++ - std::declval <T>(),SFINAE和已删除的构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47134721/