James Fan
James Fan

Reputation: 199

A function that prints different types' members

I want to write a function that accept many different types,say double and complex. I also want to print their members, say print double value when the type is double , print real and imaginary parts when this type is complex.

if I use template, there will be error, since a double cannot have real and imaginary parts at all.

say

template<class T>
void univ_print(T t)
{
if(typeid(T)==typeid(double))
printf("%f\n",t);

else if(typeid(T)==typeid(complex))
printf("%f\t%f\n",t.real, t.imag);


}

This doesn't work. So how can I obtain the effect I want.

Thanks!

Upvotes: 0

Views: 68

Answers (1)

Passer By
Passer By

Reputation: 21160

A template is more useful for cases where types share a interface

template<typename T>
T sum(T a, T b)
{
    return a + b;
}

Here, we are creating the sum function that accepts all types with the interface operator+, which includes primitives.

Now, if several types don't share a interface, what you will need to do is to specialize/overload for them. As it happens, overloading a function template is often superior to specializing.

The (almost standard) way of adding an output function to a custom type is to overload operator<< for streams.

class Complex
{
    double real, imag;
    friend std::ostream& operator<<(std::ostream& os, const Complex& c)
    {
        return os << c.real << '\t' << c.imag;
    }
    // public methods...
};

And then you can write

Complex c;
std::cout << c << std::endl;

Upvotes: 1

Related Questions