Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::variant converting constructor behavior

Tags:

c++

c++17

C++17 std::variant<class... Types> has a converting constructor

template< class T >
constexpr variant(T&& t) noexcept(/* see below */);

(number 4 in http://en.cppreference.com/w/cpp/utility/variant/variant). Its description is a rather impenetrable wall of text. Is this meant to behave as if variant had a bunch of

template< class T_i > constexpr variant(T_i&& t) noexcept;

constructors, one for each T_i in Types?

like image 303
Bulletmagnet Avatar asked Apr 28 '26 06:04

Bulletmagnet


1 Answers

Let's break the description down:

Constructs a variant holding the alternative type Tj that would be selected by overload resolution for the expression F(std::forward<T>(t)) if there was an overload of imaginary function F(Ti) for every Ti from Types... in scope at the same time.

Assume that we have the example in the documentation:

variant<string, bool> x("abc"); // OK, but chooses bool
  • Types... is <string, bool>

if there was an overload of imaginary function F(Ti) for every Ti from Types...

int F(string) { return 0; }
int F(bool)   { return 1; }

selected by overload resolution for the expression F(std::forward<T>(t))

template <typename T>
void select(T&& t)
{
    std::cout << F(std::forward<T>(t)) << '\n';
}

int main()
{
    select("abc"); // prints `1`
}

live example on wandbox


Constructs a variant holding the alternative type Tj [...]

The chosen alternative type Tj is therefore bool.

like image 70
Vittorio Romeo Avatar answered Apr 29 '26 19:04

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!