gpt4 book ai didi

c++ - 为什么编译器在执行operator<<时不能使用类的std::string转换函数?

转载 作者:行者123 更新时间:2023-12-03 06:53:37 26 4
gpt4 key购买 nike

考虑以下 struct具有用户定义的转换函数,可以将其自身转换为 const char* ;

struct S {
operator const char*() { return "hello"; }
};

这与 <iostream> 一起工作, 我们可以打印 struct S没有错误信息:

std::cout << S{} << '\n';

但是如果我将返回类型更改为 std::string :

struct S {
operator std::string() { return "hello"; }
};

我收到此编译器错误消息:

<source>:11:13: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'S')
11 | std::cout << S{} << '\n';
| ~~~~~~~~~ ^~ ~~~
| | |
| | S
| std::ostream {aka std::basic_ostream<char>}
<source>:11:18: note: 'S' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Allocator>'
11 | std::cout << S{} << '\n';
| ^

为什么编译器不能使用 std::string转换?内置类型和类类型的转换函数有区别吗?

最佳答案

因为 operator<< for std::basic_string 是一个采用 3 个模板参数的模板:

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);

并且 template argument deduction 中不会考虑隐式转换:

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

然后给出std::cout << S{}; , 模板参数 CharT , TraitsAllocator不能在第二个函数参数上推导出来。

另一方面, operator<< for const char* 没有这样的问题;给出std::cout << S{}; , 模板参数 CharTTraits只能从第一个函数参数推导出来。扣除后,隐式转换自Sconst char*将执行并且调用正常。

关于c++ - 为什么编译器在执行operator<<时不能使用类的std::string转换函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64310779/

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