【问题标题】:boost::filesystem::path::native() returns std::basic_string<wchar_t> instead of std::basic_string<char>boost::filesystem::path::native() 返回 std::basic_string<wchar_t> 而不是 std::basic_string<char>
【发布时间】:2013-08-21 19:44:36
【问题描述】:

虽然以下代码可以在 Linux 上编译,但我无法在 Windows 上编译:

boost::filesystem::path defaultSaveFilePath( base_directory );
defaultSaveFilePath = defaultSaveFilePath / "defaultfile.name";
const std::string s = defaultSaveFilePath.native();
return save(s);

其中 base_directory 是一个类的属性,它的类型是 std::string,而函数 save 只接受一个 const std::string & 作为参数。编译器报错第三行代码:

错误:要求从 'const string_type {aka const std::basic_string}' 转换为非标量类型 'const string {aka const std::basic_string}'”

对于这个软件,我同时使用 Boost 1.54(用于一些通用库)和 Qt 4.8.4(用于使用该通用库的 UI),并且我使用 MingW GCC 4.6.2 编译了所有内容。

我的 Windows Boost 版本似乎出于某种原因返回 std::basic_string。如果我的评估是正确的,我问你:如何让 Boost 返回 std::string 的实例?顺便说一句,这可能吗?

如果我对问题的评价不好,请您提供一些关于如何解决它的见解。

干杯。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    在 Windows 上,boost::filesystem 按照设计将本机路径表示为 wchar_t - 请参阅 documentation。这很有意义,因为 Windows 上的路径可以包含非 ASCII Unicode 字符。你无法改变这种行为。

    请注意,std::string 只是 std::basic_string&lt;char&gt;,并且所有本机 Windows 文件函数都可以接受宽字符路径名(只需调用 FooW() 而不是 Foo())。

    【讨论】:

    • 谢谢,这真的很有帮助。你能建议一种使这段代码更便携的方法吗?我应该在我的代码中将引用文件系统路径的字符串声明为 boost::filesystem::path::string_type 吗?这里有什么好的做法?
    • 这取决于你想对路径做什么。最便携,但最严格的事情是坚持filesystem::path 并使用boost 提供的文件操作和iostream 功能。如果您需要更具体的内容,您将失去可移植性但获得了灵活性。
    【解决方案2】:

    如何让 Boost 返回 std::string 的实例?顺便说一句,这可能吗?

    string()wstring() 函数怎么样?

    const std::string s = defaultSaveFilePath.string();
    

    还有

    const std::wstring s = defaultSaveFilePath.wstring();
    

    【讨论】:

    • 这解决了编译问题,但我想我现在主要关心的是知道是否存在以及使用 Boost Filesystem 路径对象为 Linux 和 Windows 编写可移植代码的良好做法。
    【解决方案3】:

    Boost Path 有一个简单的函数集,可以为您提供“本机”(即可移植)格式的 std::string。将make_preferredstring 结合使用。这可以在 Boost 支持的不同操作系统之间移植,并且还允许您在 std::string 中工作。

    看起来像这样:

    std::string str = (boost::filesystem::path("C:/Tools") / "svn" / "svn.exe").make_preferred().string();
    

    或者,修改原始问题的代码:

    boost::filesystem::path defaultSaveFilePath( base_directory );
    defaultSaveFilePath = defaultSaveFilePath / "defaultfile.name";
    auto p = defaultSaveFilePath.make_preferred(); // convert the path to "preferred" ("native") format.
    const std::string s = p.string(); // return the path as an "std::string"
    return save(s);
    

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2015-04-28
      • 1970-01-01
      • 2018-03-11
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多