我希望通过 SFINAE 的应用程序编译以下最小示例:
#include <iostream>
#include <string>
#include <type_traits>
struct FallBack{};
struct S {
int bar() { return 42; }
};
template <typename A, typename B>
std::enable_if_t< (std::is_same< std::enable_if_t<true==FLAG, FallBack>, FallBack>::value and std::is_convertible<B, std::string>::value), int >
foo ( A a) { return a.bar();
}
template <typename A, typename B>
std::enable_if_t<false==FLAG, int>
foo ( A a) { std::cout << "false solution " << std::endl; return -1; }
int main()
{
std::cout << foo<S, std::string>( S{}) << std::endl;
}
编译它:
g++ -std=c++14 -DFLAG=1 myFile.cc
如果我注释第二个foo
函数,一切正常,因此我对SFINAE 的理解是错误的;此外,编译器提示 foo
的定义含糊不清。
我显然错了,但看不出问题所在。 能否请任何人评论并解释为什么不应用 SFINAE?
最佳答案
您有非模板依赖条件。
你应该做类似的事情
template <typename A, typename B>
std::enable_if_t<std::is_same<A, A>::value == FLAG, int>
foo (A a) { std::cout << "false solution " << std::endl; return -1; }
关于c++ - 为什么在这个例子中没有应用 SFINAE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37746195/