mkcms mkcms - 9 months ago 31
C++ Question

Can variant<int, string> be constexpr?

From cppreference documentation for variant::variant():


This constructor is constexpr if and only if the value initialization of the alternative type T_0 would satisfy the requirements for a constexpr function.


The above says nothing about other types in the variant, so should the declaration
constexpr variant<int, string> v;
be valid if the variant must have a nontrivial destructor?

hvd hvd
Answer Source

Your quote doesn't mean the declaration constexpr variant<int, string> v; is valid. To quote N4140 (roughly C++14 rather than C++1z, but the concept hasn't changed):

7.1.5 The constexpr specifier [dcl.constexpr]

9 A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. If it is initialized by a constructor call, that call shall be a constant expression (5.19). [...]

The declaration is not valid simply by the constructor call being a constant expression, the type needs to be a literal type as well. One of the requirements of literal types is that they have trivial destructors.