std :: filesystem :: path和std :: string之间的隐式转换,应该发生吗? [英] Implicit conversion between std::filesystem::path and std::string, should it happen?

查看:1176
本文介绍了std :: filesystem :: path和std :: string之间的隐式转换,应该发生吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The cppreference page for std::filesystem::path states:

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

Paths are implicitly convertible to and from std::basic_strings, which makes it possible to use them with over files APIs, e.g. as an argument to std::ifstream::open

现在很容易看到转换为std::filesystem::path的情况,因为它具有采用std::string类型的非显式构造函数.不过,我似乎找不到的是隐式转到std::string的方法.

Now the conversion to a std::filesystem::path is easy to see as it has a non-explicit constructor that takes std::string types. What I can't seem to find, though, is a way to go to a std::string implicitly.

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

There is a string function, but it is std::string string() const;, not operator std::string(). Using

#include <filesystem>

void foo(std::string) {}

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

此代码可以使用 icc clang ,但是不能与 MSVS 一起出现错误:

this code compiles fine with icc, gcc, and clang, but not with MSVS, where it gives the error:

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

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

So, which compiler is right? Is there an implicit conversion sequence, or are the compilers just being helpful?

推荐答案

存在对std::basic_string<value_type>的隐式转换,其中value_type是与操作系统相关的字符类型.

There is an implicit conversion to std::basic_string<value_type>, where value_type is an OS-dependent character type.

然后,(我的草稿副本中的第30.10.8节,n4659)

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

For POSIX-based operating systems, value_type is char [...]
For Windows-based operating systems, value_type is wchar_t [...]

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

so there doesn't need to be an implicit conversion to std::string on Windows, only to std::wstring.

这篇关于std :: filesystem :: path和std :: string之间的隐式转换,应该发生吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆