When I have a class with templates, how can I achieve, that dependent on the dataypes, I can calculate sth. with a certain memberfunction. I constructed a minimal example where the objective is to multiply two numbers, which can either be real or complex and than take as a result only the real part of it: Re{a*b}.
This is the header file, test.hpp:
ifndef __TEST_H__
#define __TEST_H__
template<typename T1, typename T2>
class A{
public:
A(T1 const & a_, T2 const & b_);
double multiply_and_real();
private:
T1 const & a;
T2 const & b;
};
#endif /* __TEST_H__ */
And this the cpp file, test.cpp:
#include "test.hpp"
#include <complex>
#include <cmath>
template<typename T1, typename T2>
A<T1,T2>::A(T1 const & a_, T2 const & b_):
a(a_),
b(b_)
{}
template<typename T1, typename T2>
double A<double,double>::multiply_and_real(){
return a*b;
}
template<typename T1, typename T2>
double A<std::complex<double>,double>::multiply_and_real(){
return a.real()*b;
}
template<typename T1, typename T2>
double A<double,std::complex<double> >::multiply_and_real(){
return a*b.real();
}
template<typename T1, typename T2>
double A<std::complex<double>,std::complex<double> >::multiply_and_real(){
return a.real()*b.real();
}
template class A< double, double >;
template class A< std::complex<double>, double >;
template class A< double,std::complex<double> >;
template class A< std::complex<double>,std::complex<double> >;
How can I do it in the right way? With this implementation, I get errors messages of the kind:
error: prototype for ‘double A<double, double>::multiply_and_real()’ does not match any in class ‘A<double, double>’
double A<double,double>::multiply_and_real(){