我有这个成员函数测试:
template <typename T>
struct has_member {
template <typename U> static true_type f(decltype(declval<U>().member()) *);
template <typename> static false_type f(...);
static const bool value = decltype(f<T>(0))::value;
};
Run Code Online (Sandbox Code Playgroud)
当存在具有给定名称的成员函数时,如果函数具有不带参数的重载,则计算结果为true.对于这样的函数,在STL容器的情况下,除了元素访问函数(正面,背面等)之外,它的工作正常,它总是评估为false.
这是为什么?我有mingw g ++ 4.7.
那是因为这些函数返回引用,并且您声明了一个指向返回值的指针,即指向引用的指针,这是不可能的.
快速解决方案是:
template <typename U> static true_type
f(typename remove_reference< decltype(declval<U>().member()) >::type *);
Run Code Online (Sandbox Code Playgroud)
PS:如果强制编译器在SFINAE失败时发出错误并且你认为不应该这样做,那么这些错误可以(相对)容易解决.
我的意思是,在你的代码中,只是注释掉false_type并在编译时看到错误,这true_type是唯一的选择.在一系列毫无意义的线条之间有以下几点:
test.cpp:9:50: error: forming pointer to reference type
‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type& {aka int&}’
Run Code Online (Sandbox Code Playgroud)