c++ - 为什么 SFINAE 在这种情况下对我来说工作不正确以及如何解决它?

标签 c++ templates c++14 sfinae

我试图在 struct A 中留下一个函数 foo(打印 0),如果它的参数有模板方法 isA<void>,另一个(打印 1)如果没有。此代码(减少到下面的最小示例)编译(尝试使用 gcc 6.1.0 和 clang-3.9.0 以及显式 --std=c++14 选项)并运行。

但它会打印 1,但我敢肯定,它会打印 0。我想知道我哪里错了,但真正的问题是:如何使这项工作正确?

请仅使用 C++14 解决方案。

#include <type_traits>
#include <iostream>
#include <utility>

using std::enable_if;
using std::declval;
using std::true_type;
using std::false_type;
using std::cout;

template<int M>
struct ObjectX
{
  template<typename C>
  bool isA() { return false; }
};

struct XX : ObjectX<23456> {
  int af;
};

template <typename ObjType> using has_dep = decltype(declval<ObjType>().template isA<void>());

template <typename, typename = void>
struct has_isa : public false_type {};

template <typename ObjType>
struct has_isa<ObjType, has_dep<ObjType> > : public true_type {};

template<typename ObjType>
struct A
{
  template<typename T = void>
  typename enable_if<has_isa<ObjType>::value, T>::type
  foo() {
    cout << "called foo #0" << "\n";
  }

  template<typename T = void>
  typename enable_if<!has_isa<ObjType>::value, T>::type
  foo() {
    cout << "called foo #1" << "\n";
  }
};

int
main()
{
  A<XX> axx;
  // XX().template isA<void>(); -- to check, that we can call it and it exists
  axx.foo();
  return 0;
}

最佳答案

这个程序有两个问题。


首先,has_dep<XX>bool .当我们尝试 has_dep<XX> , 添加默认模板参数意味着这真的是 has_dep<XX, void> .但是特化是has_dep<XX, bool> - 这与我们实际查找的内容不符。 bool不匹配 void .这就是为什么 has_dep<XX>false_type .解决方案是 std::void_t ,我建议通读该问答以了解其工作原理。在您的特化中,您需要使用 void_t<has_dep<ObjType>>相反。


其次,这是不对的:

template<typename T = void>
typename enable_if<has_isa<ObjType>::value, T>::type

SFINAE 只发生在替换的直接上下文中,类模板参数不在函数模板替换的直接上下文中。这里的正确模式是:

template <typename T = ObjType> // default to class template parameter
enable_if_t<has_isa<T>>         // use the function template parameter to SFINAE
foo() { ... }

修复这两个问题,程序就会按预期运行。

关于c++ - 为什么 SFINAE 在这种情况下对我来说工作不正确以及如何解决它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119723/

相关文章:

c++ - 同时具有指针类型和常规类型的类模板

c++ - c++ 1y标准中是否会引入等效的双整数

c++ - 如何在运行时生成函数?

c++ - 当 static_cast'ing 为仅移动类型时,Clang 与 GCC

c++ - C/C++ 中的 C 风格无符号字符解析和操作 - 段错误

c++ - 全局变量和类内部变量有什么区别?

c++ - 尝试登录 Visual Studio 时出现 "Permission Denied"

c# - 如何为 WPF 属性制作模板?

c++ - 如何从 OpenCV C++ 中的图像中裁剪特定的矩形部分(ROI)

用于大型 HTML/XML 的 Python 模板