There is the complex<>
template in C++ standard library, and it has an overloaded << operator so that it outputs complex numbers in the (real_part, im_part) format. I need to change the behavior of that operator for complex numbers so that the output format is changed to something completely different. Specifically, I need the output to be in the form real_part\tim_part
. How do I do that?
-
1To what? You cold want to truncate the number or want it to print `pears!` every time, you need to specify. – GManNickG Feb 14 '11 at 07:05
5 Answers
There's no direct way to replace operator <<
, but you do have a few options. First, you could just write your own function to print complex numbers:
template <typename T> void PrintComplex(const complex<T>& c) {
/* ... */
}
If you want to still use the nice stream syntax, then one trick you could do would be to make a wrapper class that wraps a complex
and then defines its own operator <<
that prints it out in a different way. For example:
template <typename T> class ComplexPrinter {
public:
/* Conversion constructor allows for implicit conversions from
* complex<T> to ComplexPrinter<T>.
*/
ComplexPrinter(const complex<T>& value) : c(value) {
// Handled in initializer list
}
/* Output the complex in your own format. */
friend ostream& operator<< (ostream& out, const ComplexPrinter& cp) {
/* ... print in your own format ... */
}
private:
complex<T> c;
};
Once you have this, you could write something like
cout << ComplexPrinter<double>(myComplex) << endl;
You can make this even cleaner by writing a function like this one to wrap the object for you:
template <typename T>
ComplexPrinter<T> wrap(const complex<T>& c) {
return ComplexPrinter<T>(c);
}
This then lets you write
cout << wrap(myComplex) << endl;
Which isn't perfect, but is pretty good.
One thing to note about the above wrapper is that it has an implicit conversion constructor set up to let you convert complex<T>
s to ComplexPrinter<T>
s. This means that if you have a vector< complex<T> >
, you can print it out using your custom code by calling
vector< complex<double> > v = /* ... */
copy (v.begin(), v.end(), ostream_iterator< ComplexPrinter<double> >(cout, " "));
On output, the implicit conversion constructor will transform your complex<double>
s into the wrappers, and your custom code will do the printing for you.
If you want to be very adventurous and cast caution to the wind, you could even write the class so that it just stores a reference to the original complex
, as shown here:
template <typename T> class ComplexPrinter {
public:
/* Conversion constructor allows for implicit conversions from
* complex<T> to ComplexPrinter<T>.
*/
ComplexPrinter(const complex<T>& value) : c(value) {
// Handled in initializer list
}
/* Output the complex in your own format. */
friend ostream& operator<< (ostream& out, const ComplexPrinter& cp) {
/* ... print in your own format ... */
}
private:
const complex<T>& c;
};
This completely eliminates any copying and just makes the wrapper a thin veneer around a real complex
. (No pun intended). You'd have to be very careful if you did this not to pass these objects around across scope boundaries where the original objects go out of scope, but if it's what you want it might work out just great.
Hope this helps!

- 362,284
- 104
- 897
- 1,065
-
there actually is kind of a way to replace the `operator<<` for specific types.. https://stackoverflow.com/questions/40245110/c-display-complex-number-with-i-in-imaginary-part/52892522#52892522 – tesch1 Oct 19 '18 at 12:47
template<class T>
struct my_complex_format_type {
std::complex<T> const &x;
my_complex_format_type(std::complex<T> const &x) : x (x) {}
friend std::ostream& operator<<(std::ostream &out,
my_complex_format_type const &value)
{
out << "format value.x however you like";
return out;
}
};
template<class T>
my_complex_format_type<T> my_complex_format(std::complex<T> const &x) {
return x;
}
void example() {
std::cout << my_complex_format(some_complex);
}

- 13,952
- 4
- 37
- 63
-
Not to say that this isn't a great answer, but isn't this pretty much exactly what I posted a few minutes ago? :-) – templatetypedef Feb 14 '11 at 07:11
-
@templatetypedef: I started reading this question then typing my answer several minutes before you posted, and only hit submit 67 seconds after you. Is that a problem? – Fred Nurk Feb 14 '11 at 07:16
-
@Fred Nurk- My apologies, that wasn't meant to be confrontational. I was actually glad that we'd converged on the same answer... it means that this is probably a really good design! – templatetypedef Feb 14 '11 at 07:22
-
@templatetypedef: I'm just confused why you'd "point out" (or "accuse", though I didn't interpret you as being too confrontational in the first comment) an answer of being close to your own. This is a decent design: it's the general pattern for all stateful manipulators (stateless manipulators, such as endl, being functions). – Fred Nurk Feb 14 '11 at 07:26
-
@Fred Nurk- You're right - I was way out of line with that comment. I certainly don't want to start any hostilities between us, and I'll be sure not to do that again. As for this particular pattern, I've actually never seen it used before, though I could see it being really useful. I periodically teach a C++ programming class, and I might bring this up when talking about operator overloading as a cool example of how flexible it can be. – templatetypedef Feb 14 '11 at 07:31
-
@templatetypedef: I didn't interpret you as being too confrontational in the first comment; I was confused why you had pointed it out, that's all. It seems questions are frequently answered with very similar answers. – Fred Nurk Feb 14 '11 at 07:33
For any specific instantiation of complex<T>
, Use a strong typedef (boost has a version) and cast to that type during << calls. Override << for that type.
If you need to override << for any variation of complex<T>
then life will be harder.

- 40,307
- 7
- 73
- 125
My answer to the same question here: c++ display complex number with i in imaginary part produces the behavior you want, at the expense of some risk of future incompatibility because it inserts a template specialization into the std::
namespace.

- 2,756
- 1
- 14
- 11
-
or less kludge-y like this: https://gist.github.com/tesch1/50fa836e72153113fe56b14a61c8a4b6 – tesch1 Oct 22 '18 at 13:39
There is no really tidy way to do that. My suggestion would be to just ditch iostreams and write something more C-like instead. It will probably be faster to write, faster to read and faster to execute.

- 25,185
- 9
- 78
- 101
-
+1: C++ output formatting stinks. I remember the introduction to IO streams in TC++PL where Stroustrup starts by telling that it's not easy to write a library that will please everyone. It's more or less like starting a joke by telling that probably not everyone will like it... – 6502 Feb 14 '11 at 07:43
-
@6502: I agree that iostreams stink, but this use case is actually tidy. – Fred Nurk Feb 14 '11 at 08:10
-
-1, std::complex is a classic example where `printf()` formatting breaks down. – MSalters Feb 14 '11 at 08:55
-
@Fred Nurk: Apparently tidyness is in the eye of the beholder. I consider `printf("%0.6f\t%0.6f", double(x.real()), double(x.imag()));` so much cleaner that your 15-lines blurb of boilerplate that is not actually even doing the formatting. Add for example the equivalent of "%0.6f" for some really (IMO) horrid stuff. Note that I'm not of course saying that it's your fault... it's just that C++ formatting sucks bad. That kind of code is harder to write, harder to read, takes longer to compile, generates bigger programs and runs slower. – 6502 Feb 14 '11 at 20:30