gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:45:14 25 4
gpt4 key购买 nike

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

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 的方法。

有一个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 ,它给出了错误:

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)

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

因此不需要隐式转换为 std::string在 Windows 上,仅发送到 std::wstring .

关于c++ - std::filesystem::path 和 std::string 之间的隐式转换,应该发生吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com