在此interview Stepanov 展示了如何在 C++ 中实现通用 max
函数。
Try to implement a simple thing in the object oriented way, say, max. I do not know how it can be done. Using generic programming I can write:
template <class StrictWeakOrdered> inline StrictWeakOrdered& max(StrictWeakOrdered& x, StrictWeakOrdered& y) { return x < y ? y : x; } and template <class StrictWeakOrdered> inline const StrictWeakOrdered& max(const StrictWeakOrdered& x, const StrictWeakOrdered& y) { return x < y ? y : x; }
(you do need both & and const &).
为什么要写两次代码?这是否需要帮助编译器进行优化或减少错误的约定? max
是 const
版本的主体相同的特例吗?
一个有 N 个参数的函数应该有多少个有效的 const
和非 const
排列才能定义一个完整的 API?
最佳答案
首先,您需要非 const
版本来允许类似
max(a, b) = something;
如果你不想做这样的事情,你可以只提供 const
版本来覆盖所有情况。这基本上就是标准 std::max
所做的。
您也不需要再提供 const
和非 const
的排列,返回非 const&
仅在所有条件下才有意义输入是非const
,所有其他情况都由const
版本正确处理。
如果你想避免代码重复,你可以这样做:
template <class StrictWeakOrdered>
inline StrictWeakOrdered& max(StrictWeakOrdered& x, StrictWeakOrdered& y) {
const auto &xr = x;
const auto &yr = y;
return const_cast<StrictWeakOrdered&>(max(xr, yr));
}
在这种特殊情况下,const_cast
是安全的,因为您已经知道输入实际上是非 const
。现在您只需提供 const
案例的实现。
因此,不需要提供两次实现,也不应该对编译器有帮助,但上述内容是否比 Stepanov 所做的更具可读性是值得商榷的。
关于c++ - 为什么 const 引用参数需要重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35119819/