使用模板专业化

时间:2014-11-10 13:00:43

标签: c++ templates c++11 template-specialization

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

template<typename T>
struct X{};

template<>
struct X<int>{};

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

template<typename T>
using YetAnotherVector = std::vector<T>

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

template<>
using YetAnotherVector<int> = AFancyIntVector;

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

2 个答案:

答案 0 :(得分:7)

没有

但您可以将别名定义为:

template<typename T>
using YetAnotherVector = typename std::conditional<
                                     std::is_same<T,int>::value, 
                                     AFancyIntVector, 
                                     std::vector<T>
                                     >::type;

希望有所帮助。

答案 1 :(得分:1)

既不明确也不部分地专门化它们。 [temp.decls] / 3:

  

因为 alias-declaration 无法声明 template-id ,所以   不可能部分或明确地专门化别名模板。

您必须将专业化推迟到类模板。例如。与conditional

template<typename T>
using YetAnotherVector = std::conditional_t< std::is_same<T, int>{}, 
                                             AFancyIntVector, 
                                             std::vector<T> >;