Here's a simple example:
class bar {};
template <typename>
class foo {};
template <>
using foo<int> = bar;
Is this allowed?
$ 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:
3 Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.
Although direct specialization of the alias is impossible, here is a workaround. (I know this is an old post but it's a useful one.)
You can create a template struct with a typedef member, and specialize the struct. You can then create an alias that refers to the typedef member.
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.
This lets you specialize foo
indirectly by specializing footype
.
You could even tidy it up further by inheriting from a remote class that automatically provides the typedef. However, some may find this more of a hassle. Personally, I like it.
template <typename T>
struct remote
{ typedef T type; };
template <>
struct footype<float> :
remote<bar> {};
foo<float> y; // y is a bar.
According to §14.7.3/1 of the standard (also referred to in this other answer), aliases are not allowed as explicit specializations :(
An explicit specialization of any of the following:
- function template
- class template
- member function of a class template
- static data member of a class template
- member class of a class template
- member class template of a class or class template
- member function template of a class or class template
can be declared[...]
来源:https://stackoverflow.com/questions/7801228/can-i-specialize-a-class-template-with-an-alias-template