6

std::filesystem::path各州的 cppreference 页面:

路径可以隐式转换为 和std::basic_strings,这使得可以将它们与文件 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);
}

这段代码可以用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

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

4

2 回答 2

12

有到 的隐式转换std::basic_string<value_type>,其中value_type是依赖于操作系统的字符类型。

而且,(我的草稿中的第 30.10.8 节,n4659)

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

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

于 2019-08-06T13:53:04.713 回答
6

所有编译器都是正确的。标准规定它应该转换为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<value_type>.

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

于 2019-08-06T13:48:27.530 回答