C++ 使用模板专门化
通常的模板结构可以专门化,例如C++ 使用模板专门化,c++,templates,c++11,template-specialization,C++,Templates,C++11,Template Specialization,通常的模板结构可以专门化,例如 template<typename T> struct X{}; template<> struct X<int>{}; 有没有一种方法可以使用类似于结构模板专门化的构造来定义这些模板的专门化?我尝试了以下方法: template<> using YetAnotherVector<int> = AFancyIntVector; 模板 使用YetAnotherVector=AFancyIntVecto
template<typename T>
struct X{};
template<>
struct X<int>{};
有没有一种方法可以使用类似于结构模板专门化的构造来定义这些模板的专门化?我尝试了以下方法:
template<>
using YetAnotherVector<int> = AFancyIntVector;
模板
使用YetAnotherVector=AFancyIntVector;
但它产生了一个编译错误。这有可能吗?没有
但您可以将别名定义为:
template<typename T>
using YetAnotherVector = typename std::conditional<
std::is_same<T,int>::value,
AFancyIntVector,
std::vector<T>
>::type;
模板
使用YetAnotherVector=typename std::conditional<
std::值是否相同,
AFancyIntVector,
向量
>::类型;
希望这有帮助。既不可能明确地专门化它们,也不可能部分地专门化它们。[临时声明]/3: 因为别名声明不能声明模板id,所以它是 无法部分或显式专门化别名模板 您必须将专门化推迟到类模板。例如:
模板
使用YetAnotherVector=std::conditional_t;
AFAIK,您确实需要一个后端类。隐藏一个专门的struct
,然后使用该类生成别名。不确定我是否遵循,typedef YetAnotherVector AFancyIntVector
有什么问题?@Mr.kbok:将语句与using一起使用会导致编译错误“一次声明中的多个类型”@Mr.kbok,OP希望YetAnotherVector
是std::vector
,但是YetAnotherVector
是AFancyIntVector
。克里斯:好的,我是用另一种方式得到的std::conditional
现在踢了我很多次屁股,我都数不清了。可能是因为它的名字不好如果_else
(或者如果_c
)会更好吗?@Quentin,在c++14中会更好一些:std::conditional\u t
@chris我指的是通过分支来模拟专门化:如果你使用c++14,那么你也可以避免编写::value
部分,因为std::is same{}}
更短@纳瓦兹:我不仅关心短小,还关心清晰。无论如何,如果人们觉得可读,我会适当地编辑代码嗯,你确实关心短小,这就是为什么你写了\t
版本的std::conditional
@Nawaz No,这是因为可读性(=清晰性)conditional\u t
比typename conditional::type
更具可读性,你不认为吗?而且你认为{}
版本在清晰度方面并不更好吗?想想很多元编程和它占用的水平空间吧!
template<typename T>
using YetAnotherVector = typename std::conditional<
std::is_same<T,int>::value,
AFancyIntVector,
std::vector<T>
>::type;
template<typename T>
using YetAnotherVector = std::conditional_t< std::is_same<T, int>{},
AFancyIntVector,
std::vector<T> >;