为什么隐式转换为std :: string不适用于operator <<被调用

Zip*_*Sun 1 c++ type-conversion implicit-conversion

首先,我使用的用户定义的转换功能,以隐式转换的目的是int,然后将其插入至cout<<运营商.程序编译成功并打印为"0".

#include <iostream>

using namespace std;

class T {
public:
    operator int () {
        return 0;
    }
};

int main()
{
    T a;
    cout << a << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试做同样的事情,除了对象被转换为std::string.该程序出现编译错误.

#include <iostream>
#include <string>

using namespace std;

class T {
public:
    operator string () {
        return "";
    }
};

int main()
{
    T a;
    cout << a << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么在第二种情况下不会发生隐式转换.

son*_*yao 7

为什么在第二种情况下不会发生隐式转换.

因为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);
Run Code Online (Sandbox Code Playgroud)

这意味着T a; cout << a << endl;,为了调用它,需要推导出所有三个模板参数.但是在模板参数推导中,不会考虑隐式转换,然后推导失败.

类型推导不考虑隐式转换(上面列出的类型调整除外):这是重载解析的工作,稍后会发生.

另一方面,std::basic_ostream::operator<<(int)是非模板函数; 它没有这样的问题.