3

指定されたポインタ型がそうであるかどうかを確認するメタプログラムを実装しようとして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)) };  
};

また、コンパイラ エラー メッセージは次のとおりです。

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

あなたのコードには 2 つの問題があります。

まず、以下

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 に答える
1

問題は次のとおりです。

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

をインスタンス化するis_const<int*>と、関数定義は次のように展開されます。

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

ただし、一時的なアイテム ( TYPE it) は、int*指定したようにタイプです。check次のように、関数シグネチャを変更してポインター指定子を削除する必要があります。

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