std :: filesystem :: path和std :: string之间的隐式转换,应该发生吗?

Nat*_*ica 2 c++ path language-lawyer implicit-conversion std-filesystem

状态的cppreference页面std::filesystem::path

路径可以隐式转换为from和from std::basic_strings,因此可以将它们与over files API一起使用,例如,作为std::ifstream::open

现在,转换为a 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);
}
Run Code Online (Sandbox Code Playgroud)

这段代码可以使用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
Run Code Online (Sandbox Code Playgroud)

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

mol*_*ilo 7

隐式转换为std::basic_string<value_type>,其中value_type是OS依赖的字符类型。

并且,(我的草稿副本中的第30.10.8节,n4659)

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

因此,std::string在Windows上无需进行隐式转换,只需将转换为std::wstring


Som*_*ken 5

所有编译器都是正确的。它是由标准规定,它应该有一个转换到string_type

operator string_type() const;
Run Code Online (Sandbox Code Playgroud)

返回:native()

string_type 这是:

using string_type = basic_string<value_type>;
Run Code Online (Sandbox Code Playgroud)

native()

const string_type& native() const noexcept;
Run Code Online (Sandbox Code Playgroud)

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

本机格式为basic_string<value_type>

value_type但是不必一定如此char,因此到的转换std::string并不总是存在。它只被要求basic_string<>存在。