我可以使用别名模板专门化一个类模板吗?

时间:2011-10-18 00:38:24

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

这是一个简单的例子:

class bar {};

template <typename>
class foo {};

template <>
using foo<int> = bar;

这是允许的吗?

3 个答案:

答案 0 :(得分:11)

$ clang++ -std=c++0x test.cpp
test.cpp:6:1: error: explicit specialization of alias templates is not permitted
template <>
^~~~~~~~~~~
1 error generated.

参考:14.1 [temp.decls] / p3:

  

3因为别名声明不能声明模板ID,所以不是   可以部分或明确地专门化别名模板。

答案 1 :(得分:11)

虽然别名的直接专业化是不可能的,但这是一种解决方法。 (我知道这是一个老帖子,但它很有用。)

您可以使用typedef成员创建模板结构,并专门化结构。 然后,您可以创建引用typedef成员的别名。

template <typename T>
struct foobase {};

template <typename T>
struct footype
  { typedef foobase<T> type; };

struct bar {};

template <>
struct footype<int>
  { typedef bar type; };

template <typename T>
using foo = typename footype<T>::type;

foo<int> x; // x is a bar.

这使您可以通过专门化foo来间接地专门化footype

您甚至可以通过继承自动提供typedef的远程类来进一步整理它。但是,有些人可能会发现这更麻烦。就个人而言,我喜欢它。

template <typename T>
struct remote
  { typedef T type; };

template <>
struct footype<float> :
  remote<bar> {};

foo<float> y; // y is a bar.

答案 2 :(得分:7)

根据标准的§14.7.3/ 1(在此other answer中也有提及),不允许使用别名作为显式特化:(

  

以下任何一项的明确专业化:

     
      
  • 功能模板
  •   
  • 课程模板
  •   
  • 类模板的成员函数
  •   
  • 类模板的静态数据成员
  •   
  • 类模板的成员类
  •   
  • 类或类模板的成员类模板
  •   
  • 类或类模板的成员函数模板
  •   
     

可以声明[...]

相关问题