我是C ++的新手,我正在尝试使用模板但是我遇到了问题。 我要做的是:尝试使用模板计算数字的平方,并且数字可以是基本数据类型,如int,float,以及复数。我还使用模板实现了一个复杂的类,代码如下:
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);
}
我尝试使用模板专门化来处理特殊情况,但它给了我错误:
using ‘typename’ outside of template
并且模板特化方法发生错误。请指出我的错误。感谢。
答案 0 :(得分:6)
您似乎正在尝试部分专门化功能模板,这在C ++中实际上是不可能的。你想要的只是简单地重载这个函数:
template<typename T>
T square(T num) // Overload #1
{
return num * num;
}
template<typename T>
Complex<T> square(Complex<T> num) // Overload #2
{
T temp_real = num.real_*num.real_ - num.img_*num.img_;
T temp_img = 2 * num.img_ * num.real_;
return Complex<T>(temp_real, temp_img);
}
非正式地,当参数类型为Complex<T>
时,编译器将始终在重载#1上选择重载#2,因为它是更好的匹配。
使这项工作的另一种方法是使用the definition of multiplication for complex numbers重载Complex<>
类的乘法运算符。这样做的优点是更加通用,您可以将这个想法扩展到其他运营商。
template <typename T>
class Complex
{
public:
T real_;
T img_;
Complex(T real, T img) : real_(real), img_(img) {}
Complex operator*(Complex rhs) // overloaded the multiplication operator
{
return Complex(real_*rhs.real_ - img_*rhs.img_,
img_*rhs.real_ + real_*rhs.img_);
}
};
// No overload needed. This will work for numeric types and Complex<>.
template<typename T>
T square(T num)
{
return num * num;
}
由于您不熟悉C ++,我强烈建议您选择a good introductory C++ book。模板和运算符重载并不是初学者的主题。