-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Updated String library to use C++11 iterators. #2179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
This will allow using the String library in a ranged for loop: ```C++ String s = "Hi, this is a test"; for( char c : s ) Serial.print( c ); ```
I wanted to have the begin and end function return types based of the c_str function, however it seems not possible due to String being incomplete at this point in code. auto end() -> decltype( ((String*)nullptr)->c_str() ) { return c_str() + length(); } However I left it in to clearly show that it is a C++11 feature ( new declaration syntax ). I chose this because many Arduino libs have begin() as a method to delay construction and avoid the static initialization order problems, however this begin has quite a different meaning. What do you think is best? maybe a comment above the lines showing that they are intended for ranged loops, and not construction/initialization of something. |
As I was not able to base the return types of `begin()` & `end()` off the c_str() function, I have changed the source so the features can be used by C++98 code, while still allowing ranged loops in C++11.
As C++98 code does use begin and end for stl iterators, and because the dependency for c_str() is not possible, I have re-written them into functions usable by both 98 and 11 standards. |
Sounds good. |
This update does not need to wait until C++11 is turned on. It can be of use now, just like STL containers: for( char *ptr = s.begin() ; ptr != s.end() ; *ptr++ = /* modify each character in string */ ); It might be worth noting if documented, that end() returns the null pointer, so the loop above and a C++11 ranged loop do not include the null in the iteration. |
Now that C++11 has been enabled, can this be merged too! |
Rebased and merged, thanks @Chris--A ! |
This will allow using the String library in a ranged for loop. Also the additions expose the first and last character pointers, which may be of use somewhere.
This modification is placed inside the check for C++11 which is also due for update here: matthijskooijman@6624d61