如果你可以修改去改变着签名,这样只有两个常引用,并返回一个固定参考(除非该类型是builtin_max
然后方式足够小以至于通过值传递是有意义的),并且重载它的非常量版本。然后,您可以轻松调整签名:转发呼叫。
fract const & builtin_max(fract const & lhs, fract const & rhs);
fract & builtin_max(fract & lhs, fract & rhs);
template <>
fract const & std::max(fract const & lhs, fract const & rhs) {
return builtin_max(lhs, rhs);
}
template <>
fract & std::max(fract & lhs, fract & rhs) {
return builtin_max(lhs, rhs);
}
另一个简单的事情,你可以做不超载std::max
而是你的命名空间内制作自己max
功能。所有使用值的max
的不合格用途将在他们尝试使用std::max
默认模板之前找到您的max
函数。话又说回来,这将不完全合格的呼叫工作std::max
:
namespace x {
class fract;
fract max(fract lhs, fract rhs) { return builtin_max(lhs, rhs); }
}
// force a link time error if fully qualified std::max is used (undefined)
// instead of silently getting std::max to use < (if it is defined)
// if there is no operator<(fract const &, fract const &), leave this out
// to get an earlier compile time error
template <> fract const & std::max(fract const &, fract const &);
template <> fract & std::max(fract &, fract &);
int main() {
using namespace std;
fract a,b;
max(a, b); // x::max
// std::max(a, b) // ouch, link time error
}
我试过了,但编译器不支持它。 – 2010-07-26 10:33:37
@kotlinski这是否意味着fract没有复制构造函数?或者你的问题是RVO不会发生? – SadSido 2010-07-26 10:38:22
它有一个复制构造函数。我的猜测是RVO不会发生,或者编译器在发出警告时没有对其进行说明。 – 2010-07-26 10:43:25