此结构继承的类型是什么? [英] What is the Type This struct is Inheriting From?

查看:93
本文介绍了此结构继承的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例来自:

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...>;

在此处将其构造为r值:

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);

我试图弄清楚它是如何工作的. overloaded从这里继承的类型是什么?似乎是一个lambda数组,但我不知道它怎么会有operator().有人可以解释继承在这里如何工作吗?

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?

推荐答案

overloaded分别从每个lambda继承,并且每个lambda都有一个调用运算符.因此,您将创建一个结构,该结构在一个重载集中包含所有调用运算符.只要它们不是模棱两可的,就会自动选择正确的对象.

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();
    };

除了在实际代码中,它不会起作用,因为具有相同主体的lambda仍然具有不同的类型.

Except in real code it wouldn't work because the lambdas with the same body would still have different types.

它创建1个overloaded类型,每个实例具有多个继承.

It creates 1 overloaded type with multiple inheritance per instantiation.

这篇关于此结构继承的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆