c++ - 为什么 SFINAE 技巧在尝试类成员指针时不适用于非类类型?

标签 c++ templates compiler-errors sfinae

出于好奇,我正在尝试 is_class 的替代实现使用 sizeof() 构建诡计。以下是代码:

template<typename T>
struct is_class
{
  typedef char (&yes)[7];
  typedef char (&no)[3];

  static yes check (int T::*);
  static no check (...);

  enum { value = (sizeof(check(0)) == sizeof(yes)) };
};

问题是当我实例化 is_class<int> 时,它给出了编译错误:

error: creating pointer to member of non-class type ‘int’

现在,我的问题是,如果 int T::*不适用于 int (或 void* 等)那么为什么 不替换失败 yes check .编译器不应该选择 no check

最佳答案

yesno 不是模板,SFINAE 不可能应用于它们。你需要这样做:

template<typename T>
struct is_class
{
  typedef char (&yes)[7];
  typedef char (&no)[3];

  template <typename U>
  static yes check (int U::*);

  template <typename>
  static no check (...);

  enum { value = (sizeof(check<T>(0)) == sizeof(yes)) };
};

现在 SFINAE 可以开始了。

关于c++ - 为什么 SFINAE 技巧在尝试类成员指针时不适用于非类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6563734/

相关文章:

c++ - 在 TCP 输入或文件更新上使用 boost :asio with select? 阻塞

Code::Blocks 13.12 错误 - CC1.exe 已停止工作

C 错误 : request for member ___ in something not a structure or union

c++ - 将 lambda 传递给模板函数

C++ 函数模板问题

c++ - 获取 Base 任何子类的类

c++ - C++ 中的运算符 [&]

c++ - 为什么 C++ 链接几乎不使用 CPU?

c++ - 为什么 g++ 优化了以下代码的关键部分?

c# - MSMQ c++ 到 c# 问题