这个结构继承的类型是什么?
What is the Type This struct is Inheriting From?
所以this example from: http://en.cppreference.com/w/cpp/utility/variant/visit声明了特殊类型:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
这里构造为 r 值:
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()
。有人可以解释继承在这里是如何工作的吗?
overloaded
分别继承自每个 lambda,每个 lambda 都有一个调用运算符。因此,您创建了一个在一个重载集中包含所有调用运算符的结构。只要没有歧义,就会自动选对的。
你可以想象可变参数模板扩展到
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 仍然具有不同的类型。
它创建 1 个 overloaded
类型,每个实例化具有多重继承。
所以this example from: http://en.cppreference.com/w/cpp/utility/variant/visit声明了特殊类型:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
这里构造为 r 值:
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()
。有人可以解释继承在这里是如何工作的吗?
overloaded
分别继承自每个 lambda,每个 lambda 都有一个调用运算符。因此,您创建了一个在一个重载集中包含所有调用运算符的结构。只要没有歧义,就会自动选对的。
你可以想象可变参数模板扩展到
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 仍然具有不同的类型。
它创建 1 个 overloaded
类型,每个实例化具有多重继承。