Can I specialize a class template with an alias template?

坚强是说给别人听的谎言 提交于 2019-11-27 15:05:33

问题


Here's a simple example:

class bar {};

template <typename>
class foo {};

template <>
using foo<int> = bar;

Is this allowed?


回答1:


$ 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.




回答2:


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.



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!