我有一个实现公共string
转换成员函数的类。当与结合使用时operator<<(iostream &, xxx)
,我期望我的类将自动(隐式)转换为string
适合于参数类型。
但是,事实并非如此。为什么,我不想编写operation<<
函数。
#include <string>
#include <iostream>
using namespace std;
struct A {
operator string() { return "asd"; }
};
int main() {
cout << A() << endl; // error
cout << string(A()) << endl; // ok
}
该operator<<
对std::string
是一个模板,隐式转换不会被视为模板参数推导,这将失败。
类型推导不考虑隐式转换(上面列出的类型调整除外):这是超载解析的工作,稍后会发生。
如您所显示,您可以显式转换A
为std::string
,或编写operator<<
for A
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句