我可以用别名模板专门化一个类模板吗?
Can I specialize a class template with an alias template?
下面是一个简单的例子:
class bar {};
template <typename>
class foo {};
template <>
using foo<int> = bar;
允许吗?
$ clang++ -std=c++0x test.cpp
test.cpp:6:1: error: explicit specialization of alias templates is not permitted
template <>
^~~~~~~~~~~
1 error generated.
Reference: 14.1 [temp.decls]/p3:
因为别名声明不能声明模板id,所以它不是模板id可以部分地或显式地专门化别名模板。
虽然别名的直接专门化是不可能的,但这里有一个解决方法。(我知道这是一个旧的帖子,但它是一个有用的。)
可以用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.
这允许通过专门化footype
来间接专门化foo
。
您甚至可以通过继承自动提供类型定义的远程类来进一步整理它。然而,有些人可能会觉得这更麻烦。就我个人而言,我喜欢它。
template <typename T>
struct remote
{ typedef T type; };
template <>
struct footype<float> :
remote<bar> {};
foo<float> y; // y is a bar.
根据标准§14.7.3/1,别名不允许作为显式专门化:(
下列任意项的显式专门化:
- 函数模板
类模板- 类模板的成员函数
- 类模板的静态数据成员
- 类模板的成员类
- 类或类模板的成员类模板
- 类或类模板的成员函数模板
可以声明为[…]
相关文章:
- 别名一个模板函数,该功能没有参数可更简洁
- 成员模板别名与另一个模板成员
- 如何在C 中为多个类创建一个别名
- 创建一个从一种类型到另一种类型的别名
- 将预定但非初始化的向量设置为另一个别名
- 如何在c中给出一个函数的别名
- 依赖于参数的查找在来自另一个命名空间的别名类型上意外行为
- 如何使用模板别名删除一个不必要的参数
- C++11中一个专用模板的名称别名
- 专用模板是命名空间别名实际上是一个别名
- 从成员函数指针到另一个类型的强制转换,返回严格的别名问题
- 一个命名空间有多个别名
- 是否可以在googleprotobuf中为类型(枚举或消息)定义一个别名
- 为singleton实例调用函数创建一个别名
- 将参数包从一个模板复制到另一个模板,并在内部别名中同时使用结果
- 我可以用别名模板专门化一个类模板吗?
- 能否在c++中向前声明一个命名空间别名?
- 一个空的别名shared_ptr是一个很好的替代无操作删除shared_ptr吗?
- 模板别名为另一个别名
- 将两个目录合并到一个虚拟目录中用于编译/别名包含目录