C++ 如何 typedef 模板类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6907194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to typedef a template class?
提问by iammilind
How should I typedef
a template class
? Something like:
我应该怎么typedef
做template class
?就像是:
typedef std::vector myVector; // <--- compiler error
I know of 2 ways:
我知道两种方式:
(1) #define myVector std::vector // not so good
(2) template<typename T>
struct myVector { typedef std::vector<T> type; }; // verbose
Do we have anything better in C++0x ?
我们在 C++0x 中有什么更好的吗?
回答by Travis Gockel
Yes. It is called an "alias template," and it's a new feature in C++11.
是的。它被称为“别名模板”,它是 C++11 中的一个新特性。
template<typename T>
using MyVector = std::vector<T, MyCustomAllocator<T>>;
Usage would then be exactly as you expect:
用法将完全符合您的预期:
MyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>>
GCC has supported it since 4.7, Clang has it since 3.0, and MSVC has it in 2013 SP4.
GCC 从 4.7 开始支持,Clang 从 3.0 开始支持,MSVC 在 2013 SP4 开始支持。
回答by dascandy
In C++03 you can inherit from a class (publically or privately) to do so.
在 C++03 中,您可以从类(公开或私有)继承来执行此操作。
template <typename T>
class MyVector : public std::vector<T, MyCustomAllocator<T> > {};
You need to do a bit more work (Specifically, copy constructors, assignment operators) but it's quite doable.
您需要做更多的工作(特别是复制构造函数、赋值运算符),但这非常可行。