【问题标题】:using template specialization使用模板特化
【发布时间】:2014-11-10 13:00:42
【问题描述】:

通常的模板结构可以被特化,例如,

template<typename T>
struct X{};

template<>
struct X<int>{};

C++11 为我们提供了新的很酷的 using 语法来表达模板类型定义:

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

有没有办法为这些使用类似于结构模板的特化的构造来定义模板特化?我尝试了以下方法:

template<>
using YetAnotherVector<int> = AFancyIntVector;

但它产生了编译错误。这有可能吗?

【问题讨论】:

  • AFAIK,你确实需要一个后端类。隐藏专门的struct,然后使用该类创建别名。
  • 不确定我是否关注,typedef YetAnotherVector&lt;int&gt; AFancyIntVector 有什么问题?
  • @Mr.kbok:将您的语句与 using 一起使用会导致编译错误“多个类型在一个声明中”
  • @Mr.kbok,OP 希望YetAnotherVector&lt;T&gt; 成为std::vector&lt;T&gt;,但YetAnotherVector&lt;int&gt; 成为AFancyIntVector
  • chris:好的,我反其道而行之。 :)

标签: c++ templates c++11 template-specialization


【解决方案1】:

没有。

但您可以将别名定义为:

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

希望对您有所帮助。

【讨论】:

  • std::conditional 踢了我很多次,我都数不清了。
  • 可能是因为它有一个的名字。 if_else(或if_c)会更好吗?
  • @Quentin,在 C++14 中要好一些:std::conditional_t&lt;std::is_same_v&lt;T, int&gt;, AFancyIntVector, std::vector&lt;T&gt;&gt;
  • @chris 我指的是通过分支来模拟专业化:p
【解决方案2】:

既不能明确地专门化它们,也不能部分地专门化它们。 [temp.decls]/3:

因为 alias-declaration 不能声明 template-id,所以它是 无法部分或显式特化别名模板。

您将不得不将专业化推迟到类模板。例如。 conditional:

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

【讨论】:

  • 如果您使用的是 C++14,那么您也可以避免编写 ::value 部分,因为 std::is_same&lt;T,int&gt;{} 更短!
  • @Nawaz 我不仅关心简短,还关心清晰度。无论如何,如果人们觉得它可读,我会适当地编辑代码
  • 嗯,你确实在乎短小,这就是你写_t 版本的std::conditional 的原因。
  • @Nawaz 不,这是因为可读性(=清晰度)。 conditional_t&lt;…&gt;typename conditional&lt;…&gt;::type 更具可读性,你不觉得吗?
  • 您认为{} 版本在清晰度方面不是更好吗?想想很多元编程和它占用的水平空间!
猜你喜欢
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多