这个问题在这里已有答案:
我怎么应该typedef
template class
?就像是:
typedef std::vector myVector; // <--- compiler error
我知道两种方式:
(1) #define myVector std::vector // not so good
(2) template<typename T>
struct myVector { typedef std::vector<T> type; }; // verbose
我们在C ++ 0x中有更好的东西吗?
是。它被称为“alias template”,它是C ++ 11中的一个新功能。
template<typename T>
using MyVector = std::vector<T, MyCustomAllocator<T>>;
然后用法完全符合您的预期:
MyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>>
GCC自4.7以来一直支持它,Clang从3.0开始支持它,MSVC在2013年SP4中支持它。
在C ++ 03中,您可以从类(公开或私有)继承来执行此操作。
template <typename T>
class MyVector : public std::vector<T, MyCustomAllocator<T> > {};
你需要做更多的工作(具体来说,复制构造函数,赋值运算符),但它是非常可行的。