英文:
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
循环调用范围表达式上的begin
和end
(在这种情况下将是您的类类型,可能会有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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论