C++类型转换时定义非成员函数
作者:fatalerror99 来源:BLOG 添加时间:2006-5-26 10:33:22《C++箴言:声明为非成员函数的时机》阐述了为什么只有 non-member functions(非成员函数)适合于应用到所有 arguments(实参)的 implicit type conversions(隐式类型转换),而且它还作为一个示例使用了一个 Rational class 的 operator* function。我建议你在阅读本文之前先熟悉那个示例,因为本文进行了针对《C++箴言:声明为非成员函数的时机》中的示例做了一个无伤大雅(模板化 Rational 和 operator*)的扩展讨论:
| template class Rational { public: Rational(const T& numerator = 0, // see《C++箴言:用传引用给const取代传值》for why params const T& denominator = 1); // are now passed by reference const T numerator() const; // see《C++箴言:避免返回对象内部构件的句柄》for why return const T denominator() const; // values are still passed by value, ... // Item 3 for why they're const }; template const Rational const Rational { ... } |
就像在《C++箴言:声明为非成员函数的时机》中,我想要支持 mixed-mode arithmetic(混合模式运算),所以我们要让下面这些代码能够编译。我们指望它能,因为我们使用了和 Item 24 中可以工作的代码相同的代码。仅有的区别是 Rational 和 operator* 现在是 templates(模板):
| Rational // except Rational is now a template Rational |
编译失败的事实暗示对于模板化 Rational 来说,有某些东西和 non-template(非模板)版本不同,而且确实存在。在《C++箴言:声明为非成员函数的时机》中,编译器知道我们想要调用什么函数(取得两个 Rationals 的 operator*),但是在这里,编译器不知道我们想要调用哪个函数。作为替代,它们试图断定要从名为 operator* 的 template(模板)中实例化出(也就是创建)什么函数。它们知道它们假定实例化出的某个名为 operator* 的函数取得两个 Rational
在推演 T 的尝试中,它们会察看被传入 operator* 的调用的 arguments(实参)的类型。在当前情况下,类型为 Rational
使用 oneHalf 的推演很简单。operator* 的第一个 parameter(形参)被声明为 Rational