Nico Schlömer Nico Schlömer - 4 months ago 17
C++ Question

Nonmember template function

I have a templated class

pair
, and I'd like to write a
show
function outside of the class to do some fancy
cout
ing. When specifying the template type in
show
explictly, it all works as expected:



#include <iostream>

template <class A_Type>
class pair
{
public:
A_Type a0;
A_Type a1;
};

void show(const pair<double> & p) {
std::cout << p.a0 << std::endl;
std::cout << p.a1 << std::endl;
}

int main() {
pair<double> p;
p.a0 = 1.2;
p.a1 = 1.3;

show(p);
}


I'd like to have
show
oblivious of the template type though.

Any hints?

Answer

You can change show function to:

template<typename DataType>
void show(const pair<DataType> & p) {
   std::cout << p.a0 << std::endl;
   std::cout << p.a1 << std::endl;
}

Or a better approach (in my opinion) is to make show function member of the class:

template <class A_Type>
class pair {
   public:
     A_Type a0;
     A_Type a1;

     void show() const {
         std::cout << this->a0 << std::endl;
         std::cout << this->a1 << std::endl;
     }
};

and then simply:

int main() {
   pair<double> p;
   p.a0 = 1.2;
   p.a1 = 1.3;

   p.show();
}