Home > Software design >  Defaulted template argument in std::optional constructor
Defaulted template argument in std::optional constructor

Time:11-22

std::optional has the following constructor:

template < class U = T >
constexpr optional( U&& value );

The question here is: why template parameter U is defaulted to type T? What happens if simply change constructor to following:

template < class U /* = T */>
constexpr optional( U&& value );

CodePudding user response:

It's so if you give it an initializer list (which doesn't have a type, so can't infer a type for U), it will initialize a T temporary.

For example:

std::optional<std::vector<int>> opt({1, 2, 3});
// No type deduced for `U`, defaults to `std::vector<int>`

struct X {
    int a, b;
};
std::optional<X> opt({.a = 1, .b = 2});
// Same here
  • Related