What is the difference between path::string() and path::generic_string() in boost?

前端 未结 2 1921
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 00:08

What is the difference between boost::path::string() and boost::path::generic_string(), and when should I use each of them?

2条回答
  •  遇见更好的自我
    2021-01-19 00:45

    Reading your mind, you are programming on a Windows system.

    On your system, as far as boost can tell, the preferred separator between path elements is \. However, / is an acceptable separator.

    The constructor to boost::fs::path docs state:

    [Note: For ISO/IEC 9945 and Windows implementations, the generic format is already acceptable as a native format, so no generic to native conversion is performed. --end note]

    Note the clause about Windows implementations -- the generic format (with / separators) is already acceptable, so no conversion is done.

    Then when you invoke t/fn the appends or / or /= operator is used. It states:

    [Note: For ISO/IEC 9945-like implementations, including Unix variants, Linux, and Mac OS X, the preferred directory separator is a single forward slash.

    For Windows-like implementations, including Cygwin and MinGW, the preferred directory separator is a single backslash.--end note]

    And the preferred separator is \ on windows systems.

    So at construction, no conversion from generic to system occurs -- but on appending with operator/ or similar, it is.

    This results in your string looking ugly.

    If you want to fix the problem, you could iterate over your 'malformed' path using begin and end, and store/append the elements into a new path using operator/.

    boost::fs::path fix( boost::fs::path in ) {
      boost::fs::path retval;
      for ( auto element : in ) {
        if (retval.empty())
          retval = in;
        else
          retval /= in;
      }
      return retval;
    }
    

    which if I read the docs right will take your mixed-slash path and generate a clean one.

    If you are stuck in C++03 iterate over in using in.begin() and in.end() and boost::fs::path::iterator.

提交回复
热议问题