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

标签 c++ type-conversion implicit-conversion

起初,我使用用户定义的转换函数将对象隐式转换为 int然后将其插入 cout<<运算符(operator)。程序编译成功并打印'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;
}

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

最佳答案

Why implicit conversion doesn't happen on the second case.

因为 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; ,要调用它,需要推导所有三个模板参数。但是在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::basic_ostream::operator<<(int) 是一个非模板函数;它没有这样的问题。

关于c++ - 为什么隐式转换为 std::string 不适用于调用 operator<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616713/

相关文章:

java - 在 :each 中动态转换托管项目

c++ - 为什么这个volatile变量的地址一直是1?

objective-c - 子类的 Swift 数组处理

c++ - arduino (esp8266/esp32) 股票回调类成员函数

c++ - 'this' 参数的类型为 const 但函数未标记为 const C++ 重载运算符

c++ - 对返回和参数类型的混淆

c# - "Prefix"和 "as"转换

c++ - 如何在 Qt 中动态添加选项卡?

c++ - 使用 GLSL 的 OpenGL 3.3 中的纹理显示为黑色

python - Python-无法在此特定代码中将int隐式转换为str