Sha*_*ang 4 c++ templates specialization
我是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);
}
Run Code Online (Sandbox Code Playgroud)
我试图使用模板专门化来处理特殊情况,但它给了我错误:
using ‘typename’ outside of template
Run Code Online (Sandbox Code Playgroud)
并且错误发生在模板特化方法上.请指出我的错误.谢谢.
您似乎正在尝试部分专门化功能模板,这在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);
}
Run Code Online (Sandbox Code Playgroud)
非正式地,当参数是类型时,编译器将始终在重载#1上选择重载#2,Complex<T>因为它是更好的匹配.
另一种使这项工作的方法是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;
}
Run Code Online (Sandbox Code Playgroud)
由于您是C++的新手,我强烈建议您选择一本好的C++入门书.模板和运算符重载并不是初学者的主题.
| 归档时间: |
|
| 查看次数: |
1565 次 |
| 最近记录: |