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

Implicit conversion between std::filesystem::path and std::string, should it happen?

本文关键字:std 转换 ath filesystem string 之间      更新时间:2023-10-16

std::filesystem::path的cpp首选项页面指出:

路径可以隐式地与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);
}

这段代码在ICC,GCC和CLANG上编译得很好,但在MSVS上则不能,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

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

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

并且,(§30.10.8 在我的草稿副本中,n4659(

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

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

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