【问题标题】:c++ template specialization method questionc++模板特化方法题
【发布时间】:2011-07-12 09:59:26
【问题描述】:

我是 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

并且错误发生在模板专业化方法上。请指出我的错误。谢谢。

【问题讨论】:

  • 不是答案,但请注意&lt;complex&gt; 标头,它可能完全不需要任何代码。

标签: c++ templates specialization


【解决方案1】:

您似乎正在尝试部分专门化函数模板,这在 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&lt;T&gt; 时,编译器将始终选择重载#2 而不是重载#1,因为它是更好的匹配。


实现这项工作的另一种方法是使用the definition of multiplication for complex numbers 重载Complex&lt;&gt; 类的乘法运算符。这具有更通用的优点,您可以将此想法扩展到其他运算符。

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。模板和运算符重载并不完全是初学者的主题。

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 2016-12-25
    • 2012-01-09
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多