[英]Why can't the compiler use the std::string conversion function of the class when perform operator<<?
Consider the following struct
with a user-defined conversion function that can convert itself to const char*
;考虑以下带有用户定义转换函数的
struct
,该函数可以将自身转换为const char*
;
struct S {
operator const char*() { return "hello"; }
};
This work with <iostream>
, we can print the struct S
with no error message:这与
<iostream>
一起工作,我们可以打印struct S
没有错误消息:
std::cout << S{} << '\n';
But if I change the return type to std::string
:但是,如果我将返回类型更改为
std::string
:
struct S {
operator std::string() { return "hello"; }
};
I got this compiler error message:我收到此编译器错误消息:
<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';
| ^
Why can't the compiler use the std::string
conversion?为什么编译器不能使用
std::string
转换? Is there a difference between the conversion function of the built-in and class type?内置和类类型的转换函数有区别吗?
Because operator<<
for std::basic_string
is a template taking 3 template parameters:因为
std::basic_string
operator<<
是一个带有 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);
And implicit conversion won't be considered in 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.
类型推导不考虑隐式转换(上面列出的类型调整除外):这是重载解析的工作,稍后发生。
Then given std::cout << S{};
然后给定
std::cout << S{};
, the template parameter CharT
, Traits
and Allocator
can't be deduced on the 2nd function argument. ,模板参数
CharT
、 Traits
和Allocator
不能在第二个函数参数上推导出来。
On the other hand, operator<<
for const char*
doesn't have such issue;另一方面,
const char*
operator<<
没有这样的问题; given std::cout << S{};
给定
std::cout << S{};
, the template parameter CharT
and Traits
would be deduced only from the 1st function argument. ,模板参数
CharT
和Traits
只能从第一个函数参数中推导出来。 After deduction, the implicit conversion from S
to const char*
will be performed and the calling works well.推导后,将执行从
S
到const char*
的隐式转换,调用效果良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.