为什么SFINAE会导致编译器出错?

iam*_*ind 3 c++ templates compiler-errors sfinae

我试图实现一个元程序,它找到给定的指针类型是否const.即

  • is_const<TYPE*>::value 应该 false
  • is_const<const TYPE*>::value 应该 true

以下是代码:

template<class TYPE>
struct is_const
{
  typedef char yes[3];
  template<typename T>
  struct Perform
  {
    static yes& check (const T*&);
    static char check (T*&);
  };  

  TYPE it; 
  enum { value = (sizeof(Perform<TYPE>::check(it)) == sizeof(yes)) };  
};
Run Code Online (Sandbox Code Playgroud)

编译器错误消息是:

In instantiation of ‘is_const<int*>’:
instantiated from here
error: no matching function for call to ‘is_const<int*>::Perform<int*>::check(int*&)’
note: candidates are: static char (& is_const<TYPE>::Perform<T>::check(const T*&))[3] [with T = int*, TYPE = int*]
note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
Run Code Online (Sandbox Code Playgroud)

我的重点已转移到错误消息.如果你看到最后一行:

note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
Run Code Online (Sandbox Code Playgroud)

如果我们真正取代T = int*TYPE = int*那就真的应该匹配相应的函数(char check()).我很想知道这里出了什么问题.

Ker*_* SB 9

为什么这么迂回?一个直截了当的特质课怎么样:

#include <functional>

template <typename T> struct is_const_ptr : std::false_type { };
template <typename T> struct is_const_ptr<const T *> : std::true_type { };

struct Foo {};

int main()
{
  std::cout << is_const_ptr<Foo*>::value << is_const_ptr<const Foo*>::value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)