[C++] 重载 / 并作为路径连接运算符

陪她去流浪 桃子 2018年05月03日 阅读次数:2045

今天在看 EOS柚子 的源代码的时候,看到这样一句:

auto wallet_filename = dir / (name + file_ext);

其中的变量类型如下:

boost::filesystem::path dir;
const std::string& name
constexpr auto file_ext = ".wallet";

一开始的时候还有点懵,虽然自己没有这样写过。但还是能猜测到作用:/ 被重载了,用于路径的连接

突然感觉有点惊喜似的?,自己以前写代码也经常重载运算符,但是重载/作为路径连接还真没这样搞过,骚操作!

于是,翻阅源代码,发现:这是 Boost C++ 库实现的,详见:boost/filesystem/path.hpp - 1.61.0

inline path operator/(const path& lhs, const path& rhs)  { return path(lhs) /= rhs; }

template <class Source>
    typename boost::enable_if<path_traits::is_pathable<
    typename boost::decay<Source>::type>, path&>::type
operator/=(Source const& source)
{
    return append(source);
}

快半年没写 C++ 了,一翻大神的代码,就又学到了新东西???

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。

标签:EOS · Boost