using template specialization

一曲冷凌霜 提交于 2021-02-07 12:58:25

问题


Usual template structs can be specialized, e.g.,

template<typename T>
struct X{};

template<>
struct X<int>{};

C++11 gave us the new cool using syntax for expressing template typedefs:

template<typename T>
using YetAnotherVector = std::vector<T>

Is there a way to define a template specialization for these using constructs similar to specializations for struct templates? I tried the following:

template<>
using YetAnotherVector<int> = AFancyIntVector;

but it yielded a compile error. Is this possible somehow?


回答1:


No.

But you can define the alias as:

template<typename T>
using YetAnotherVector = typename std::conditional<
                                     std::is_same<T,int>::value, 
                                     AFancyIntVector, 
                                     std::vector<T>
                                     >::type;

Hope that helps.




回答2:


It's neither possible to specialize them explicitly nor partially. [temp.decls]/3:

Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.

You will have to defer specializations to class templates. E.g. with conditional:

template<typename T>
using YetAnotherVector = std::conditional_t< std::is_same<T, int>{}, 
                                             AFancyIntVector, 
                                             std::vector<T> >;


来源:https://stackoverflow.com/questions/26844443/using-template-specialization

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