《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 operator*(const Rational& lhs, const Rational& rhs) { ... } |
就像在《C++箴言:声明为非成员函数的时机》中,我想要支持 mixed-mode arithmetic(混合模式运算),所以我们要让下面这些代码能够编译。我们指望它能,因为我们使用了和 Item 24 中可以工作的代码相同的代码。仅有的区别是 Rational 和 operator* 现在是 templates(模板):
Rational oneHalf(1, 2); // this example is from 《C++箴言:声明为非成员函数的时机》, // except Rational is now a template
Rational result = oneHalf * 2; // error! won't compile |
编译失败的事实暗示对于模板化 Rational 来说,有某些东西和 non-template(非模板)版本不同,而且确实存在。在《C++箴言:声明为非成员函数的时机》中,编译器知道我们想要调用什么函数(取得两个 Rationals 的 operator*),但是在这里,编译器不知道我们想要调用哪个函数。作为替代,它们试图断定要从名为 operator* 的 template(模板)中实例化出(也就是创建)什么函数。它们知道它们假定实例化出的某个名为 operator* 的函数取得两个 Rational 类型的参数,但是为了做这个实例化,它们必须断定 T 是什么。问题在于,它们做不到。
在推演 T 的尝试中,它们会察看被传入 operator* 的调用的 arguments(实参)的类型。在当前情况下,类型为 Rational(oneHalf 的类型)和 int(2 的类型)。每一个参数被分别考察。 使用 oneHalf 的推演很简单。operator* 的第一个 parameter(形参)被声明为 Rational 类型,而传入 operator* 的第一个 argument(实参)(oneHalf) 是 Rational 类型,所以 T 一定是 int。不幸的是,对其它参数的推演没那么简单。operator* 的第二个 parameter(形参)被声明为 Rational 类型,但是传入 operator* 的第二个 argument(实参)(2) 的 int 类型。在这种情况下,让编译器如何断定 T 是什么呢?你可能期望它们会使用 Rational 的 non-explicit constructor(非显式构造函数)将2 转换成一个 Rational,这样就使它们推演出 T 是 int,但是它们不这样做。它们不这样做是因为在 template argument deduction(模板实参推演)过程中从不考虑 implicit type conversion functions(隐式类型转换函数)。
1
2
3
4
下一页>>
|