模板typedef与std :: vector有自定义分配器

时间:2017-12-20 08:39:07

标签: c++ templates g++ typedef c++03

我想定义一个自定义向量类,它使用带有自定义分配器的std :: vector类,如下所示:

template <class T>
typedef std::vector<T, MyLib::MyAlloc<T> > my_vector;

然后,当我尝试将其用作:

  my_vector<std::string> v;

我在Linux 10上的g ++ 2.95.3编译器抱怨说

 template declaration of `typedef class vector<T,MyLib::MyAlloc<T1> > my_vector'
aggregate `class my_vector<basic_string<char,string_char_traits<char>,__default_alloc_template<false,0> > > v' has incomplete type and cannot be initialized

请帮我纠正这个片段。

1 个答案:

答案 0 :(得分:2)

C ++ 11通过&#34; new&#34;支持这一点。类型别名语法:

template <class T>
using my_vector = std::vector<T, MyLib::MyAlloc<T> >;

&#34; old&#34; form(typedef)不能用于创建别名模板。

如果不是C ++ 11或更高版本。唯一的办法是模板元功能:

template <class T>
struct my_vector {
  typedef std::vector<T, MyLib::MyAlloc<T> > type;
};

可以这样使用:

my_vector<std::string>::type v;

或者,因为std::vector是类类型:

template <class T>
struct my_vector : std::vector<T, MyLib::MyAlloc<T> > {};

可以使用哪种方式,因为您最初希望使用它。

相关问题