以前的operator overload 可能是这样的。
struct PrintVisitor
{
void operator()(int& i) const {
std::cout << "int: " << i;
}
void operator()(float& f) const {
std::cout << "float: " << f;
}
void operator()(std::string& s) const {
std::cout << "string: " << s;
}
};
std::variant<int, float, std::string> intFloatString { "Hello" };
std::visit(PrintVisitor(), intFloatString);
有了C++17 的 Overload Pattern 之后 就可以这样写了。看起来很难懂, 但是代码比较简洁了。
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>;
std::variant<int, float> intFloat { 0.0f };
std::visit(overload(
[](const int& i) { ... },
[](const float& f) { ... },
),
intFloat;
);
更多细节的可以参考 https://dev.to/fenbf/2-lines-of-code-and-3-c-17-features-the-overload-pattern-pgg