Appending to boost::filesystem::path

后端 未结 5 1230
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 00:53

I have a certain boost::filesystem::path in hand and I\'d like to append a string (or path) to it.

boost::filesystem::path p(\"c:\\\\dir\");
p.appen         


        
5条回答
  •  时光取名叫无心
    2021-02-05 01:29

    You can define the + operator yourself such that you can add two boost::filesystem::path variables.

    inline boost::filesystem::path operator+(boost::filesystem::path left, boost::filesystem::path right){return boost::filesystem::path(left)+=right;}
    

    Then you can even add a std::string variable (implicit conversion). This is similar to the definition of the operator/ from

    include/boost/filesystem/path.hpp:

    inline path operator/(const path& lhs, const path& rhs)  { return path(lhs) /= rhs; }
    

    Here is a working example:

    main.cpp:

    #include 
    #include 
    #include 
    
    using namespace boost::filesystem;
    inline path operator+(path left, path right){return path(left)+=right;}
    
    int main() {
      path p1 = "/base/path";
      path p2 = "/add/this";
      std::string extension=".ext";
      std::cout << p1+p2+extension << '\n';
      return 0;
    }
    

    compiled with

    g++ main.cpp -lboost_system -lboost_filesystem
    

    produces the output:

    $ ./a.out 
    "/base/path/add/this.ext"
    

提交回复
热议问题