将运算符<<与隐式转换的非基本数据类型一起使用时出错

Error when using operator << with implicitly converted non-fundamental data types

本文关键字:lt 一起 数据类型 出错 运算符 转换      更新时间:2023-10-16

我有一个结构,可以用作其他类型的包装器,如下所示:

template<typename T>
struct A {
A& operator=(const T& value){
m_value = value;
return *this;
}
operator T() const {
return m_value;
}
private:
T m_value;
};

我是这样使用它的:

int main() {
A<int> a;
a = 5;                  // Copy assignment constructor
std::cout << a << "n"; // Implicit conversion to int
}

按预期工作。使用非基本类型时会出现我的问题,如以下示例所示:

int main() {
A<std::complex<int>> c;
c = std::complex<int>(2, 2);  
std::cout << c << "n";
}

上面的代码段引发了一个invalid operands to binary expression错误。

为什么会发生此错误?为什么std::complex<int>的重载运算符<<不与隐式转换的A<std::complex<int>>一起使用?

std::complex的流运算符是模板函数。 除非您实际有std::complex,否则不会调用它们,因为在模板参数扣除中不会发生转换。 这意味着编译器将找不到合适的重载来打印A<std::complex<int>>

您是作品的第一种情况,因为std::basic_ostream::operator <<过载以采用int,并且允许您使用一个用户定义的转换是重载分辨率。


作为工作循环,您可以定义自己的operator <<,该将包装器转发到底层类型的operator <<。 那看起来像

template<typename T>
std::ostream& operator <<(std::ostream& os, const A<T>& a)
{
return os << static_cast<T>(a);
}