3

我试图实现一个元程序,它会发现给定的指针类型是否const存在。IE

  • 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)) };  
};

编译器错误消息是:

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*]

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

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

如果我们真的替换T = int*然后TYPE = int*它真的应该匹配适当的函数(char check())。我很想知道这里出了什么问题。

4

3 回答 3

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;
}
于 2011-07-05T17:22:37.473 回答
1

这是你的问题:

static yes& check (const T*&);
static char check (T*&);

当您实例化时is_const<int*>,您的函数定义将扩展为:

static yes& check (const int**&);
static char check (int**&);

但是,您的临时项目 ( TYPE it) 是 type int*,就像您指定的那样。您需要更改check函数签名以删除指针说明符,如下所示:

static yes& check (const T&);
static char check (T&);
于 2011-07-05T17:27:35.093 回答
1

您的代码中有两处错误。

一、以下

static yes& check (const T*&);
static char check (T*&);

必须改为

static yes& check (const T&);
static char check (T&);

第二,it会员必须是static

static TYPE it;

或者,只是传递((TYPE)0)给您的检查功能。不需要会员。

于 2011-07-05T17:30:31.473 回答