c ++使用嵌套模板类来传递类型信息

ian*_*itz 4 c++ templates

可能重复:
我必须在何处以及为何要使用"template"和"typename"关键字?

当我尝试在VS 2012中编译以下代码时,我在Consumer类的typedef行中得到错误,从以下开始:

error C2143: syntax error : missing ';' before '<'
Run Code Online (Sandbox Code Playgroud)

这是编译器的问题还是代码不再有效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;
};
Run Code Online (Sandbox Code Playgroud)

有一个解决方法,但我只是想知道是否应该要求:

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;
};
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 8

您需要帮助编译器知道这Container是一个模板:

template<class Provider>
class Consumer 
{
  typedef typename Provider:: template Container<int>::type intContainer;
  typedef typename Provider:: template Container<double>::type doubleContainer;
};
Run Code Online (Sandbox Code Playgroud)

SO帖子的公认答案中对此进行了很好的解释.