【发布时间】:2013-10-28 17:15:05
【问题描述】:
想尝试一下,我最近决定尝试在 C++ 中实现一个模板化的复数类。作为参考,我使用了 C++ 11 标准库实现,我发现该实现与我的实现之间存在差异。它指的是他们如何在他们的类中重载 += 运算符。
我基本上只有一个 += 方法,可以同时处理 Complex<T> += Complex<U> 和 Complex<T> += whatever other type that implicitly converts to T and thus Complex<T>。为了澄清,这里是类声明:
template <typename T>
class Complex {
public:
constexpr Complex (T=T(), T=T()); // added for clarity
template <typename U>
constexpr Complex (const Complex <U>&);
template <typename U>
constexpr Complex (Complex <U>&&);
template <typename U>
Complex <T>& operator= (const Complex <U>&);
template <typename U>
Complex <T>& operator= (Complex <U>&&);
Complex& operator+= (const Complex<T>&);
Complex& operator-= (const Complex<T>&);
Complex& operator*= (const Complex<T>&);
Complex& operator/= (const Complex<T>&);
Complex& operator++ (void);
Complex operator++ (int);
Complex& operator-- (void);
Complex operator-- (int);
std::string to_string (void) const;
constexpr T real (void);
constexpr T img (void);
void real (const T&);
void img (const T&);
private:
T _m_real, _m_img;
template <typename U>
friend class Complex;
};
但是在标准库实现中,它们为operator+= 使用了2 个重载,一个采用Complex<U>,另一个采用T。就我测试而言,这两种实现似乎都产生了相同的行为:任何两个复杂类型之间的加法,或者一个复杂类型和另一个隐式转换为复杂内部类型的类型之间的加法。
所以,我的问题是:除了优化临时复合体以及如果所有其他复合体类型都隐式转换为 Complex 时为什么要使用嵌套 template <typename U> 之外,还有什么理由需要单独的 operator+=(T)?
【问题讨论】:
-
complex< T > & operator+=(const T & t)仅将t添加到复数的 Re 部分。实际上,t是一个复数,其中 Im 部分等于0。complex< T > & operator-=(const T & t)也是如此。您可以在complex标头中亲自查看。 -
您的标量 ctor 的签名丢失了吗?演员中是否缺少
=0? -
是的,我在编辑中解决了这个问题。它在实现中,没有添加到声明中。
标签: c++ templates overloading implicit-conversion