iam*_*ind 71 c++ templates typedef c++11
我typedef该template class怎么办?就像是:
typedef std::vector myVector; // <--- compiler error
Run Code Online (Sandbox Code Playgroud)
我知道两种方式:
(1) #define myVector std::vector // not so good
(2) template<typename T>
struct myVector { typedef std::vector<T> type; }; // verbose
Run Code Online (Sandbox Code Playgroud)
我们在C++ 0x中有更好的东西吗?
Tra*_*kel 124
是.它被称为" 别名模板 ",它是C++ 11中的一个新功能.
template<typename T>
using MyVector = std::vector<T, MyCustomAllocator<T>>;
Run Code Online (Sandbox Code Playgroud)
然后用法完全符合您的预期:
MyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>>
Run Code Online (Sandbox Code Playgroud)
GCC自4.7以来一直支持它,Clang从3.0开始支持它,MSVC在2013年SP4中支持它.
das*_*ndy 15
在C++ 03中,您可以从类(公开或私有)继承来执行此操作.
template <typename T>
class MyVector : public std::vector<T, MyCustomAllocator<T> > {};
Run Code Online (Sandbox Code Playgroud)
你需要做更多的工作(具体来说,复制构造函数,赋值运算符),但它是非常可行的.