为了在C++11中进行方法检测,我使用了SFINAE,我编写了这个运行中的小示例:
#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, "");问题:解释以及如何解决?
发布于 2017-11-06 10:27:16
当空构造函数被删除时,构造:
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
{
};解决了问题。
吸取的教训:
decltype(Foo().my_method()); // invalid
decltype(std::declval<Foo>().my_method()); // fine是不对等的。
发布于 2017-11-06 10:36:40
此外,还有一种方法可以定义不需要引用或指向对象的指针,也不需要函数的特定签名的测试:
template<class T>
typename std::is_member_function_pointer<decltype(&T::my_method)>::type test_member_function_my_method(int);
template<class T>
std::false_type test_member_function_my_method(...);
template<class T>
using has_member_function_my_method = decltype(test_member_function_my_method<T>(0));用法:
static_assert(!has_member_function_my_method<double>::value, "");
static_assert(has_member_function_my_method<Foo>::value, "");https://stackoverflow.com/questions/47134721
复制相似问题