$cat test.cc
#include <type_traits>
struct foo{
};
template<typename F,typename A>
struct other
{
template<typename f, typename a,
#ifndef PASS
typename = decltype(std::declval<F>()(std::declval<A>()))>
#else
typename = decltype(std::declval<f>()(std::declval<a>()))>
#endif
static std::true_type _Fn(int);
template<typename...>
static std::false_type _Fn(...);
typedef decltype(_Fn<F,A>(0)) type;
};
int main() {
static_assert(std::is_same<std::false_type,other<foo&,int>::type>::value,"PASSED");
return 0;
}
Compilation command:
g++ test.cc -std=c++11
为什么没有-dpass的sfinae不能在这里工作? 我正在努力编译原始的测试用例(没有-dpass),但是我想出了解决方案(-dpass),但是我不能理解其中的区别?
因为与类方法相关的SFINAE在方法本身的模板参数上工作,而不是在包含类的方法上工作。
您可以通过以下技巧绕过这个限制,在方法参数中“转换”类参数
template <typename T>
struct foo
{
template <typename U = T,
typename = /* some test over U */>
void bar ();
// ...
这样,u
是方法bar
的模板参数,但其类型与类t
的模板参数相同。