2

I'm pretty sure that it is impossible but just to get a certainty - is it possible to invoke different unary operator* "overloads"(?) on the iterator of the collection depending on used type in a ranged based for. I'm especially interested in invoking two different overloads for:

for (auto &e: collection)

and

for (auto e: collection)

But the question can be more generalized for given type of e.

15
  • 1
    'Is it possible...' -> have you tried that? Did it work? If no, what isn't working as expected?
    – ForceBru
    May 9, 2016 at 16:11
  • 1
    How are the operators overloaded? May 9, 2016 at 16:15
  • @ForceBru As I said - I'm pretty sure that it is impossible cause I don't even know what syntax would it involve... The question raised while implementing a trie collection for my purpose...
    – W.F.
    May 9, 2016 at 16:15
  • The question doesn't make sense since ranged-based fors don't give you direct access to the iterator. May 9, 2016 at 16:15
  • 1
    You could simply avoid auto here and use an explicit wrapper object to call the correct overload. May 9, 2016 at 16:19

1 Answer 1

1

I am not aware that it is possible.

But you can get similar behaviour by iterating over different proxy objects:

for (auto &&e: collection.method1())
// ...
for (auto &&e: collection.method2())

The proxy objects returned by method1 and method2 implement begin and end function that return different types of iterators, which implement operator* differently.

2
  • 3
    @WojciechFrohmberg, well. An adapter class over a standard container may be possible. method1(std_container). And will in fact extend to any "stl"-like object, such as the boost containers. May 9, 2016 at 16:35
  • 1
    @StoryTeller There is interesting article How Non-Member Functions Improve Encapsulation: If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions. May 10, 2016 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.