首页 > 解决方案 > filesystem::operator/ boost 和 std 中的不同行为

问题描述

我正在尝试从 移植boost::filesystemstd::filesystem。在此过程中,我遇到了一些代码,其中boost似乎std以不同的方式运行。

以下代码显示了该行为:

#include <iostream>
#include <filesystem>
#include <boost/filesystem.hpp>

template<typename T>
void TestOperatorSlash()
{
    const std::string foo = "Foo";
    const std::string bar = "Bar";
    const T start = "\\";
    std::string sep;
    sep += T::preferred_separator;
    const auto output = start / (foo + bar) / sep;
    std::cout << output << '\n';
}

int main(int argc, char** argv)
{
    TestOperatorSlash<std::filesystem::path>();
    TestOperatorSlash<boost::filesystem::path>();
}

代码在输出中给出:

"\\"
"\FooBar\"

对我来说,预期的行为是boost,我不明白 会发生什么std::filesystem

为什么我会得到"\\"?为什么 和的operator/行为path不同?booststd

编辑:

在了解了行为的动机std::filesystem::operator/并给出了这个问题的答案后,我决定使用该函数作为我何时拥有绝对路径path::relative_path()的第二个参数。operator/

通过这种方式,我可以模仿boost::filesystem. 因此,例如:

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char** argv)
{
    fs::path foo = "\\foo";
    fs::path bar = "\\bar";
    auto foobar0 = foo / bar;                   // Evaluates to \\bar
    auto foobar1  = foo / bar.relative_path();  // Evaluates to \\foo\\bar
}

标签: c++boostfilesystemsstd

解决方案


Boost 将合并多余的分隔符。

https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/reference.html#path-appends

将 path::preferred_separator 附加到路径名,如果需要,转换格式和编码 ([path.arg.convert]),除非:

an added separator would be redundant, ...

而 std::filesystem 将第二个参数中的前导分隔符/视为替换部分或全部原始路径的指令:

https://en.cppreference.com/w/cpp/filesystem/path/append

path("C:foo") / "/bar";  // yields "C:/bar"        (removes relative path, then appends)

你想要:

const auto output = start / (foo + bar) / "";

反而?


推荐阅读