gpt4 book ai didi

c++ - 基于范围的for循环的范围表达式使用const函数重载

转载 作者:行者123 更新时间:2023-11-28 00:01:24 25 4
gpt4 key购买 nike

更新,感谢 AlexD 的回答:这个问题归结为选择成员函数重载的语言规则,在以下问题中讨论:Calling a const function rather than its non-const version


range-based for loop 的范围表达式时是对成员函数的调用 const和非 const重载,似乎非 const过载被选中。因此,以下程序无法编译:

#include <iostream>
#include <vector>

class foo {
public:
const std::vector<int>& get_numbers() const { return numbers; }
protected:
std::vector<int>& get_numbers() { return numbers; }
private:
std::vector<int> numbers;
};

int main() {
foo f;
for (int x : f.get_numbers()) std::cout << x << std::endl;
}

来自 gcc 5.3 的诊断消息:

error: ‘std::vector<int>& foo::get_numbers()’ is protected

但是一个const get_numbers() 的版本可用并且可以使用。我们可以通过使用 const 来强制使用它引用foo例如,像这样:

int main() {
foo f;
const foo& g = f;
for (int x : g.get_numbers()) std::cout << x << std::endl;
}

是否有更好/更简单的方法告诉编译器它可以并且应该使用 const成员函数重载,没有显式创建 const引用对象?

有一些similar questions关于使用基于范围的 for 循环 const迭代器,但我还没有发现任何关于制作循环范围表达式 const 的问题用于选择函数重载。

最佳答案

But a const version of get_numbers() is available and could be used.

在考虑可访问性之前选择最佳功能。标准状态(强调我的):

If a best viable function exists and is unique, overload resolution succeeds and produces it as the result. Otherwise overload resolution fails and the invocation is ill-formed. When overload resolution succeeds, and the best viable function is not accessible (Clause 11) in the context in which it is used, the program is ill-formed.

关于c++ - 基于范围的for循环的范围表达式使用const函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38753318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com