如何为类模板生成别名

How to generate alias for class templates?

本文关键字:别名      更新时间:2023-10-16

我希望MyVector可以选择std::vector或boost::container::vector。如何实现它?我可以使用宏,但我被告知它们不是很安全。谢谢。

#define MyVector std::vector
// #define MyVector boost::container::vector

c++ 11有别名模板。你可以这样做:

template <typename T>
using MyVector = std::vector<T>;
//using MyVector = boost::container::vector<T>;

然后像这样使用:

MyVector<int> x;

在c++ 03中,你可以使用宏或者元函数。

template <typename T>
struct MyVector {
    typedef std::vector<T> type;
    //typedef boost::container::vector<T> type;
};
// usage is a bit tricky
MyVector<int>::type x;
// ... or when used in a template
typename MyVector<T>::type x;