为什么隐式转换为 std::string 不适用于运算符<<被调用
Why implicit conversion to std::string doesn't work with operator<< being called
起初,我使用用户定义的转换函数将对象隐式转换为int
,然后使用运算符将其插入cout
<<
。程序编译成功并打印为"0"。
#include <iostream>
using namespace std;
class T {
public:
operator int () {
return 0;
}
};
int main()
{
T a;
cout << a << endl;
return 0;
}
然后,我尝试做同样的事情,只是将对象转换为std::string
。程序出现编译错误。
#include <iostream>
#include <string>
using namespace std;
class T {
public:
operator string () {
return "";
}
};
int main()
{
T a;
cout << a << endl;
return 0;
}
为什么隐式转换不会在第二种情况下发生。
为什么隐式转换不会在第二种情况下发生。
因为operator<<(std::basic_string)
是一个模板函数,
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);
这意味着给定T a; cout << a << endl;
,要调用它,需要推导出所有三个模板参数。但在模板参数推导中,不会考虑隐式转换,然后推导失败。
类型推断不考虑隐式转换(上面列出的类型调整除外(:这是重载解决的工作,稍后会发生。
另一方面,std::basic_ostream::operator<<(int)
是一个非模板函数;它没有这样的问题。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多