重载标准运算符<<对于std :: complex

时间:2014-11-04 22:01:32

标签: c++ c++11 operator-overloading eigen

有没有办法替换默认的

template <typename T, typename charT, typename traits> 
std::basic_ostream<charT, traits> &
operator << (std::basic_ostream<charT, traits> &strm, const std::complex<T>& c)
带有我自己版本的标准库附带的

?我不能只使用上面的签名重载它,因为编译器抱怨(并且它是正确的)关于模糊调用。我需要这样的重载,因为我希望以不同的格式显示std::complex个数字,例如a + b*i,而不是默认的(a,b)

我可以简单地这样做

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::complex<T>& c)
{
    os << real(z) << " + " << imag(z) << "i";
    return os;
}

然而,这不是std中使用的通用版本,并且不会被其他库调用,例如Eigen。

1 个答案:

答案 0 :(得分:1)

你可以做什么 - 至少因为你已经愿意采取官方禁止的方法来向namespace std添加一些与用户定义的类无关的东西 - 是明确地将它专门用于你需要的类型。

template <typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator << (std::basic_ostream<charT, traits> &strm, const std::complex<double>& c)    
{
    strm<<c.real()<<"+"<<c.imag()<<"*i";
    return strm;
}

编译器将选择完美匹配而不是模板化版本。为您需要的每种类型重载它。

但请注意,遵循C ++标准,这会产生未定义的行为,因为您可能不会向namespace std添加任何替换现有实现的内容。

尽管如此,它似乎至少在使用g ++编译器的ideone.com上工作,并且可能对其他现代编译器也是如此[此猜测基于this thread here]

相关问题