使用模板专业化

gex*_*ide 6 c++ templates template-specialization c++11

通常的模板结构可以是专门的,例如,

template<typename T>
struct X{};

template<>
struct X<int>{};
Run Code Online (Sandbox Code Playgroud)

C++ 11为我们提供了using表达模板typedef 的新酷语法:

template<typename T>
using YetAnotherVector = std::vector<T>
Run Code Online (Sandbox Code Playgroud)

有没有办法使用类似于结构模板的特化的构造为这些定义模板特化?我尝试了以下方法:

template<>
using YetAnotherVector<int> = AFancyIntVector;
Run Code Online (Sandbox Code Playgroud)

但它产生了编译错误.这有可能吗?

Naw*_*waz 7

没有.

但您可以将别名定义为:

template<typename T>
using YetAnotherVector = typename std::conditional<
                                     std::is_same<T,int>::value, 
                                     AFancyIntVector, 
                                     std::vector<T>
                                     >::type;
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

  • @Quentin,在 C++14 中更好一点:`std::conditional_t&lt;std::is_same_v&lt;T, int&gt;, AFancyIntVector, std::vector&lt;T&gt;&gt;` (2认同)