Mircea Baja
Mircea Baja

Reputation: 463

Why std::variant in C++17 allows std::variant<int, const int>

In http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0088r3.html there is a note about the need to expand on std::variant<int, const int>, and voting for allowing it, but I can't find the actual rationale.

So why would it make sense to allow for std::variant<int, const int>?

Upvotes: 3

Views: 2056

Answers (1)

bogdan
bogdan

Reputation: 9317

The rationale and discussion sections that were present in earlier versions of the paper have been separated into P0086 - Variant design review.

The relevant paragraph says:

variant<int, const int> A variant can handle const types: they can only be set through variant construction and emplace(). If both const and non-const types are alternatives, the active alternative is chosen by regular constructor instantiation / overload rules, just as for any other possibly matching alternative types.

So, in terms of rationale, looking through the section on alternatives we can say that:

  • The fewer requirements on alternative types there are, the easier it is to use variant in template code. (Otherwise, template code would have to go through a list of types, remove cv-qualifiers, eliminate duplicates, and so on before instantiating a variant with them.)
  • Allowing cv-qualified types in general, and the same type with different cv-qualifications in particular, can be implemented with semantics that flow naturally from the nature of the types.

Upvotes: 1

Related Questions