有没有办法替换默认值
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。
最佳答案
您可以做的——至少因为您已经愿意采用官方禁止的方法向 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
添加任何内容来替换现有的实现。
不过,它似乎至少在 ideone.com 上有效使用 g++ 编译器,其他现代编译器可能也是如此 [这个猜测是基于 this thread here ]
关于c++ - 为 std::complex 重载标准运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26745878/