What is the type of this Inheriting From structure?

So this example from: http://en.cppreference.com/w/cpp/utility/variant/visit declares a specialized type:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; 

What is built here as an r-value:

 std::visit(overloaded { [](auto arg) { std::cout << arg << ' '; }, [](double arg) { std::cout << std::fixed << arg << ' '; }, [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }, }, v); 

I am trying to understand how this works. What is the type that inherits overloaded ? This is similar to a lambdas array, but I do not see how it will be operator() . Can someone explain how inheritance works?

+5
source share
1 answer

overloaded inherited from each lambda separately, and each lambda has a call statement. Therefore, you create a structure that has all the call statements in one set of overloads. As long as they are not ambiguous, the correct one will be automatically selected.

You can imagine a variation template expand to

 struct overloaded : // inherits from decltype([](auto arg) { std::cout << arg << ' '; }), decltype([](double arg) { std::cout << std::fixed << arg << ' '; }), decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }) // has three operator()s { using decltype([](auto arg) { std::cout << arg << ' '; })::operator(); using decltype([](double arg) { std::cout << std::fixed << arg << ' '; })::operator(); using decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; })::operator(); }; 

Except for real code, this will not work, because lambdas with the same body will still have different types.

It creates type 1 overloaded with multiple inheritance per instance.

+6
source

Source: https://habr.com/ru/post/1268630/


All Articles