C++ 17 尝鲜之 the overload pattern

Posted by Luffyao on Sunday, December 8, 2019

简单介绍

以前在 C++98 的时候,咱们想要操作符重载怎么办?我们一般都是会将想要重载的操作符在自己的 class 或者 struct 里面写一遍。

一般大家写出来的代码无非和我的差不多。

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

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

总结

总之,C++新的标准,相对于老版本来说,高大上了不少,也更加现代化了,更加降低了使用者的入门基础了(简单的一个例子就是,以前让 C++程序员最头疼的指针,也是在 C++11 的时候引入了智能指针)。