代码之家  ›  专栏  ›  技术社区  ›  Ton van den Heuvel

为什么不能从`std::filesystem::path`迭代器构造`std::filesystem::path`?

  •  11
  • Ton van den Heuvel  · 技术社区  · 7 年前

    #include <filesystem>
    
    std::filesystem::path strip_prefix(std::filesystem::path p)
    {      
      if (auto it{p.begin()}; it != p.end())
      {
        ++it;
        return std::filesystem::path(it, p.end());
      }
    
      return p;
    }
    

    (见: https://godbolt.org/z/wkXhcw )

    我惊讶地发现这不起作用。由于路径构造函数只接受对字符序列进行迭代的迭代器,因此代码不会编译。我可以看到它的用途,但是为什么只将构造限制在这类迭代器上呢?在我看来,不支持从自己的迭代器构造路径是违反直觉的。据我所知,大多数其他STL类型都支持这种习惯用法。

    除了完全重建一条新的道路之外,实现同样目标的有效实施是什么?

    使现代化 :在这种情况下,我发现以下讨论是相关的/有趣的: http://boost.2283326.n4.nabble.com/boost-filesystem-path-frustration-td4641734.html . 我同意戴夫的看法。我认为将路径视为路径元素的容器是看待它的一种非常自然的方式(从程序员的角度)。

    1 回复  |  直到 7 年前
        1
  •  6
  •   T.C. Yksisarvinen    7 年前

    path 只是 std::accumulate()

    对于您的特定用例,我会这样做:

    std::filesystem::path strip_prefix(std::filesystem::path p)
    {
        if(p.empty()) return p;
        return std::accumulate(std::next(p.begin()), p.end(), 
                               std::filesystem::path{}, std::divides{});
    }
    

    至于为什么没有一个构造函数(或者一个自由函数)来做这件事呢?我不知道。在处理路径时,这似乎是一种需要,但如果通过调用标准算法可以获得相同的结果,委员会确实不愿意向标准类添加方便函数。

    推荐文章