c++ - filesystem::operator/ 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>();
}
代码在输出中给出:
"\\"
"\FooBar\"
对我来说,预期的行为是boost
,我不明白 会发生什么std::filesystem
。
为什么我会得到"\\"
?为什么 和的operator/
行为path
不同?boost
std
编辑:
在了解了行为的动机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
}
解决方案
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) / "";
反而?
推荐阅读
- vb.net - 从列表中移动一个项目并将其从前一个列表中删除
- python - Python舍入问题需要将每个数字舍入一半
- sql - 从标准输入 PostgreSQL 复制
- c# - 为什么我可以跳而不是走路,而不是走路而不是跳。我不知道代码有什么问题
- java - 有人知道如何在 java 泛型中制作这种类型的程序吗?
- c - “数组的元素类型不完整”错误
- python - Python mock.patch 没有模拟我的函数?
- python - Python单元测试用假替换类
- okhttp - 带有内容类型 json 的 OkHttp 响应 204
- php - 在 Wordpress 中设置 AJAX 请求的问题(使用 JQuery)