What is the Type This struct is Inheriting From?

陌路散爱 提交于 2019-12-23 10:58:38

问题


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

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

Which is constructed as an r-value here:

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'm trying to figure out how this works. What is the type that overloaded inherits from here? It seems like an array of lambdas but I don't see how that would have an operator(). Can someone explain how the inheritance is working here?


回答1:


overloaded inherits from each lambda individually and each lambda has a call operator. You therefore create a struct that has all call operators in one overload set. As long as they are not ambiguous the right one will automatically be picked.

You can imagine the variadic template to 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 in real code it wouldn't work because the lambdas with the same body would still have different types.

It creates 1 overloaded type with multiple inheritance per instantiation.



来源:https://stackoverflow.com/questions/44414606/what-is-the-type-this-struct-is-inheriting-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!