【问题标题】:Implicit conversion between std::filesystem::path and std::string, should it happen?std::filesystem::path 和 std::string 之间的隐式转换,应该发生吗?
【发布时间】:2019-12-14 02:01:28
【问题描述】:

std::filesystem::path 的 cppreference 页面指出:

路径可以隐式地与std::basic_strings 相互转换,这使得它们可以与文件API 一起使用,例如作为std::ifstream::open的参数

现在很容易看到转换为std::filesystem::path,因为它有一个采用std::string 类型的非显式构造函数。不过,我似乎无法找到一种隐式访问std::string 的方法。

有一个string 函数,但它是std::string string() const;,而不是operator std::string()。使用

#include <filesystem>

void foo(std::string) {}

int main()
{
    namespace fs = std::filesystem;
    fs::path p1;
    foo(p1);
}

此代码与iccgccclang 一起编译得很好,但与MSVS 不一样,它给出了错误:

example.cpp

<source>(10): error C2664: 'void foo(std::string)': cannot convert argument 1 from 'std::filesystem::path' to 'std::string'

<source>(10): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Compiler returned: 2

那么,哪个编译器是正确的?是否有隐式转换序列,或者编译器只是有帮助?

【问题讨论】:

    标签: c++ path language-lawyer implicit-conversion std-filesystem


    【解决方案1】:

    所有编译器都是正确的。应该是specified by the standard 转换为string_type

    operator string_type() const;
    

    返回:native()

    string_type 这里是:

    using string_type = basic_string<value_type>;
    

    还有native()

    const string_type& native() const noexcept;
    

    返回:本机格式的路径名。

    本机格式为basic_string&lt;value_type&gt;

    value_type 但是不一定是char,因此转换为std::string 并不总是存在。只要求basic_string&lt;&gt;存在一个。

    【讨论】:

      【解决方案2】:

      存在到std::basic_string&lt;value_type&gt; 的隐式转换,其中value_type 是依赖于操作系统的字符类型。

      并且,(我的草稿中的§30.10.8,n4659)

      对于基于 POSIX 的操作系统,value_type 为 char [...]
      对于基于 Windows 的操作系统,value_type 是 wchar_t [...]

      因此在 Windows 上不需要隐式转换为 std::string,只需转换为 std::wstring

      【讨论】:

        猜你喜欢
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        • 2019-11-06
        • 2021-08-21
        • 1970-01-01
        • 2018-02-18
        相关资源
        最近更新 更多