2

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 ); 
1
  • Triple backticks are only for code blocks, not inline code. Just use one for that. Commented Nov 22, 2022 at 0:25

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.