【问题标题】:Purpose of class = void in C++? [duplicate]C ++中class = void的目的? [复制]
【发布时间】:2017-10-16 22:40:42
【问题描述】:

下面代码sn-ps中class = void的作用是什么?

template< class, class = void >
struct has_type_member : false_type { };

template< class T >
struct has_type_member<T, void_t<typename T::type>> : true_type { };

【问题讨论】:

  • 这是参数的默认值
  • 即使没有class = void,它也能工作,不是吗?
  • @BЈовић 不,不会的。
  • @Barry 因为它是用 2 个模板参数调用的? OP没有说明它是如何使用的。

标签: c++ c++11 templates c++14 void


【解决方案1】:
template< class, class = void >
struct has_type_member : false_type { };

这是你的默认结构模板,它要求 2 个模板参数,但第二个默认设置为 void,所以这个参数不需要显式指定,有点像默认函数参数。

然后:

template< class T >
struct has_type_member<T, void_t<typename T::type>> : true_type { };

has_type_member 结构的模板特化,如果 T::type 不存在(因此,语法无效),SFINAE 将排除此特化,否则将选择此特化。

第二个参数是模板特化所必需的,但我们不会在“备用”struct 中使用它,所以我们只是默认为void

【讨论】:

  • 严格来说,可以通过class = std::void_t&lt;&gt; 来提示正在发生的事情。
  • 请问class = void为什么不能省略?
  • @laike9m 你需要 class 以便它是一个 2 参数模板,用于专业化。您需要 = void 以便模板的用户只传递他们感兴趣的类型。
猜你喜欢
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 2010-10-12
相关资源
最近更新 更多