c++ - 为什么 const 引用参数需要重复代码?

标签 c++

在此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 &).

为什么要写两次代码?这是否需要帮助编译器进行优化或减少错误的约定? maxconst 版本的主体相同的特例吗?

一个有 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/

相关文章:

c++ - 如何通过 memcpy 将可 move 类型推送到/从遗留的基于 C 的容器中弹出?

c++ - 在 Windows 上重建 hhvm

c++ - 不使用 For 循环将数据从指向局部数组的指针传输到全局数组

c++ - 如何从 OpenCV 中的目录中按顺序读取文件?

c++ - 使用 MFC 同步对象的陷阱

c++ - 寻找 C/C++ 语言和标准库规范

c++ - C++中的单链表赋值运算符重载

c++ - 为具有 `char` 的整数变量输入 `std::cin` 时的未定义行为

C++ 从字符串中去除非 ASCII 字符

c++ - 在 C++ for 循环中使用除 int 以外的数据类型作为索引值