A for-each loop in a templated class cannot differentiate between regular and const iterators.

huangapple go评论76阅读模式
英文:

Can a for-each loop differentiate between regular and const iterator in a templated class?

问题

我创建了一个带有两种不同迭代器的模板类,一个是常规迭代器,另一个是const迭代器。在使用for-each循环时,编译器是否根据对象的特定实例知道要使用哪个迭代器,无论它是否是const的?如果这是一个愚蠢的问题,我很抱歉,我刚开始学习C++。

英文:

I made a templated class with 2 different iterators, a regular one and a constIterator.
When using a for-each loop, does the complier know which iterator to use according to the specific instance of the object, whether it is const or not?
Sorry if this is a dumb question, I just started learning C++.

答案1

得分: 1

一个基于范围的for循环调用范围表达式上的beginend(在这种情况下将是您的类类型,可能会有const限定符)来获取迭代器。

这些函数是否返回const迭代器取决于您为您的类实现它们的方式。如果您正确实现了它们,它们应该分别具有非const重载和const重载,每个重载返回适当的迭代器类型。

英文:

A range-based for loop calls begin and end on the range expression (which would be of your class type in this case and potentially const-qualified) to obtain iterators.

Whether these functions return const iterators or not depends on how you implemented them for your class. If you implemented them correctly, they should have a non-const overload and a const overload each, with each returning the appropriate iterator type.

huangapple
  • 本文由 发表于 2023年6月5日 00:02:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定