c++ - 为什么在这个例子中没有应用 SFINAE?

标签 c++ c++14 sfinae

我希望通过 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/

相关文章:

c++ - 为什么 decltype(auto) 在这里返回一个引用?

c++ - 结合完美转发模板和任意值类型模板

c++ - VSCode 用户代码段在其他代码段中不起作用

c++ - 无法重载自定义 PriorityQueue 的提取运算符

c++ - 存在使用命名空间时的全局范围解析

c++ - 将模板参数限制为仅具有不同构造函数签名的一组类

c++ - 使用 SFINAE 检测成员函数

c++ - 为什么 SFINAE 似乎不能在此处使用 nullptr 重载?

c++ - 当子级存储在基指针 vector 上时如何从基类动态转换为子类

c++ - 如何在 catch 语句之外使用异常