0

I have defined my own character iterator class. Can I somehow plug it in to std::string so that I dont have to implement the std::string kind of interface again? I checked the template arguments of std::basic_string, but it does not take anything of this sort.

2
  • 1
    Why would you do something like this? What does your iterator class what std::string's iterators (char*) don't? Commented Dec 3, 2012 at 10:38
  • My iterator is aware of character encoding, like UTF8 while std::string is not. I cant find any other c++ std::string based implementation which is aware of character encoding. Commented Dec 3, 2012 at 17:25

2 Answers 2

1

One idea is to provide begin(std::string) and end(std::string) functions which return your iterators. These can then be used in all the places which expect iterators.

begin() free function style is from c++11 onwards.

Sign up to request clarification or add additional context in comments.

4 Comments

You can put these functions in your own namespace, but would they be found? Argument Dependent Lookup will not search your namespace.
@MSalters is there a reason it will not search my namespace? It doesnt need to be in a namespace, global namespace should do.
This is just a special case of "Custom specializations of std::begin may be provided for classes that do not expose a suitable begin() member function, yet can be iterated." right?
Not if you're talking about begin(std::string), because that class does expose a suitable .begin() member.
0

There's an overloaded constructor for std::string which will take an iterator pair. That would work, but create a copy. That is of course the best you can do. Consider an implementation which has the "Small String Optimization", i.e. a small char[N] inside the std::string object itself. That is very, very likely incompatible with your memory layout.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.