Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用模板专门化_C++_Templates_C++11_Template Specialization - Fatal编程技术网

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> >;