std::filesystem::p ath 和 std::string 之间的隐式转换,应该发生吗?
Implicit conversion between std::filesystem::path and std::string, should it happen?
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_typewchar_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<>
。
- 将无符号char*转换为std::istream*C++
- 将 int 数组转换为 std::vector<int*>
- 如何将这个std::字符串转换为std::基本字符串
- 哪些类型可以转换为std::any
- 如何在对<char>C++程序进行逆向工程的同时将 std::basic_string 转换为 Rust 可读值?
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将函数参数"const char*"转换为"std::string_view"是
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 字符转换功能 std::isupper() & std::islower() C++17
- 将函数包装器转换为 std::function
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- std::转换move构造函数的模板专业化的变体
- STD ::转换如何用特定值初始化函子
- 对C++字符串使用 std 转换
- 等价于元组的std::转换
- std::转换为任意容器
- std::转换顺序保证
- std::转换产生奇怪的输出