4

重複の可能性:
「template」および「typename」キーワードをどこに、なぜ配置する必要があるのですか?

VS 2012で次のコードをコンパイルしようとすると、Consumerクラスのtypedef行で次の文字で始まるエラーが発生します。

error C2143: syntax error : missing ';' before '<'

これはコンパイラの問題ですか、それともコードは有効ではなくなったc ++ですか?(それが抽出されたプロジェクトは、確かに古いバージョンのVS(およびgcc iirc)で問題なくビルドするために使用されましたが、それは約10年前のことです!)

struct TypeProvider
{
  template<class T> struct Container
  { 
    typedef vector<T> type; 
  };
};

template<class Provider>
class Consumer 
{
  typedef typename Provider::Container<int>::type intContainer;
  typedef typename Provider::Container<double>::type doubleContainer;
};

それには回避策がありますが、それが必要かどうか疑問に思います:

struct TypeProvider    
{
   template<typename T> struct Container { typedef vector<T> type; };
};

template<template<class T> class Container, class Obj>
struct Type
{
  typedef typename Container<Obj>::type type;
};

template<typename Provider>
class TypeConsumer
{
  typedef typename Type<Provider::Container, int>::type intContainer;
  typedef typename Type<Provider::Container, double>::type doubleContainer;
};
4

1 に答える 1

9

Containerこれがテンプレートであることをコンパイラに知らせる必要があります。

template<class Provider>
class Consumer 
{
  typedef typename Provider:: template Container<int>::type intContainer;
  typedef typename Provider:: template Container<double>::type doubleContainer;
};

これは、この SO 投稿に対する受け入れられた回答で非常によく説明されています。

于 2013-01-26T12:58:10.173 に答える