这是一个简单的例子:
class bar {};
template <typename>
class foo {};
template <>
using foo<int> = bar;
这是否允许?
最佳答案
虽然别名的直接特化是不可能的,但这里有一个解决方法。 (我知道这是一篇旧帖子,但它很有用。)
您可以使用 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
。
您甚至可以通过从自动提供 typedef 的远程类继承来进一步整理它。但是,有些人可能会觉得这更麻烦。就个人而言,我喜欢它。
template <typename T>
struct remote
{ typedef T type; };
template <>
struct footype<float> :
remote<bar> {};
foo<float> y; // y is a bar.
关于c++ - 我可以使用别名模板专门化一个类模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801228/