Void as a literal type?

柔情痞子 提交于 2019-12-08 14:54:09

问题


In C++14 void is a literal type

A type is a literal type if it is:

— void; or

— a scalar type; or

— a reference type; or

— an array of literal type; or

— a class type (Clause 9) that has all of the following properties: — it has a trivial destructor,

— it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and

— all of its non-static data members and base classes are of non-volatile literal types.

In C++11 void is not a literal type

A type is a literal type if it is:

— a scalar type; or

— a reference type referring to a literal type; or

— an array of literal type; or

— a class type (Clause 9) that has all of the following properties: — it has a trivial destructor,

— every constructor call and full-expression in the brace-or-equal-initializers for non-static data members (if any) is a constant expression (5.19),

— it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and

— all of its non-static data members and base classes are of literal types.

So why is void a literal type? What benefits does it offer?


回答1:


Since void is literal type, constexpr functions can have return type void in C++14.

It's covered in this proposal.

Quote from proposal:

An arbitrary expression-statement is permitted, in order to allow calls to functions performing checks and to allow assert-like constructs. void also becomes a literal type, so that constexpr functions which exist only to perform such checks may return void.

#define ASSERT(expr) \
  (void)((expr) || assert_failed(#expr, __LINE__, __FILE__))
void assert_failed(...); // not constexpr
struct S {
  std::array a<int, 100>;
  size_t i;

  constexpr void check_invariants() const {
    ASSERT(i < a.size());
    ASSERT(a[i] == 0);
  }
  S(std::array<int, 100> a_, size_t i_) : a(a_), i(i_) {
    check_invariants();
  }
};


来源:https://stackoverflow.com/questions/27486581/void-as-a-literal-type

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