通过使用用户定义的推导指南使lambda重载如何工作?

时间:2019-04-28 18:35:42

标签: c++ c++17

当我阅读this paper时,我发现Recursive Lambdas部分中的lambda过载。我很困惑,因为我从未见过,所以我认为这可能是C ++中一个我从未听说过的新关键字。

结果证明,它不是关键字,而是本文中未定义的辅助函数/类。我终于在cppreference.com std::visit页面上找到了一些有关它的信息。

在提供的示例中,我了解了发生的一切,除了一件事:

// helper type for the visitor #4
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
...
int main() {
...
        // 4. another type-matching visitor: a class with 3 overloaded operator()'s
        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{...})表示正在调用构造函数,但没有一个,即使调用了overloaded函数,它也没有身体。

所以,我的问题是:这里发生了什么?我发现有些参考资料正在使用用户定义的推导指南,但是我仍然不清楚。

编辑

关键是我对以下内容的误解:

template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

这不是免费的模板函数声明,而是(tl; dr)user-defined deduction guides,它声明构造函数的默认模板类参数是什么。

这与What are Aggregates and PODs and how/why are they special?几乎没有切线关系,这是该问题被标记为重复的词,并且仅在标题为What will change for C++20的答案中被简短提及。

0 个答案:

没有答案