I'm new to C++ and I'm trying to use template but I got problems. What I'm trying to do is: try to calculate square of a number using template, and the number may be basic data types like int, float, as well as complex numbers. I also implemented a complex class using template, and the codes are as follows:
template <typename T>
class Complex {
public:
T real_;
T img_;
Complex(T real, T img) : real_(real), img_(img) { }
};
template <typename T>
T square(T num) {
return num * num;
}
template <>
Complex<typename T> square(Complex<typename T> num) {
T temp_real = num.real_*num.real_ - num.img_*num.img_;
T temp_img = 2 * num.img_ * num.real_;
return Complex(temp_real, temp_img);
}
I tried to use template specialization to deal with the special case, but it gave me error:
using ‘typename’ outside of template
and the error happens on the template specialization method. Please point out my mistakes. Thanks.