Dun*_*ndo 6 c++ filesystems boost std
我正在尝试从 移植boost::filesystem到std::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>();
}
Run Code Online (Sandbox Code Playgroud)
该代码给出输出:
"\\"
"\FooBar\"
Run Code Online (Sandbox Code Playgroud)
我的预期行为是boost,我不明白 会发生什么std::filesystem。
为什么我得到"\\"?为什么和operator/的行为path不同?booststd
在了解了行为的动机并给出了这个std::filesystem::operator/问题的答案之后,我决定使用该函数作为第二个参数,当我有绝对路径时。path::relative_path()operator/
这样我就可以模仿 的行为boost::filesystem。因此,例如:
"\\"
"\FooBar\"
Run Code Online (Sandbox Code Playgroud)
小智 4
Boost 将合并多余的分隔符。
https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/reference.html#path-appends
将 path::preferred_separator 附加到路径名,根据需要转换格式和编码 ([path.arg.convert]),除非:
Run Code Online (Sandbox Code Playgroud)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)
Run Code Online (Sandbox Code Playgroud)
你想要吗:
const auto output = start / (foo + bar) / "";
Run Code Online (Sandbox Code Playgroud)
反而?