std::filesystem::path 没有运算符+?

Tou*_*dou 12 c++ std-filesystem

可以使用运算符在一行中附加/多个路径:

  std::filesystem::path p1{"A"};
  auto p2 = p1 / "B" / "C";
Run Code Online (Sandbox Code Playgroud)

这是相当方便的。然而,concat只提供+=

  std::filesystem::path p1{"A"};
  auto p2 = p1 / "B" / "C" + ".d";   // NOT OK
Run Code Online (Sandbox Code Playgroud)

这非常烦人,因为我无法轻松地将扩展添加到路径的末尾。我别无选择,只能写一些类似的东西

  std::filesystem::path p1{"A"};
  auto p2 = p1 / "B" / "C";
  p2 += ".d";
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?这种不一致有原因吗?

n31*_*159 4

这有点推测,但我认为原因是 anoperator+很容易与 混淆operator/。如果按如下方式使用,这会导致错误

path p2{"/"};
auto p1 = p2 + "A" + "B";
// Wants /A/B, gets /AB
Run Code Online (Sandbox Code Playgroud)

使用字符串文字可以使解决方法更好:

using namespace std::literals;
std::filesystem::path p1{"A"};
auto p2 = p1 / "B" / ("C"s + ".d");   
Run Code Online (Sandbox Code Playgroud)

在这里,"C"s创建一个std::stringwith contentC然后我们使用std::strings operator+。如果该"C"部分本身已经是一条路径(否则你可以直接写"C.d"),你可以这样做

std::filesystem::path p1{"A"}, c_path{"C"};
auto p2 = p1 / "B" / (c_path += ".d");   
Run Code Online (Sandbox Code Playgroud)

因为operator+=返回结果对象。(这有点浪费,但我可以想象编译器会优化它)。