I sort of assumed that range based for loops would support C-style strings
void print_C_str(const char* str)
{
for(char c : str)
{
cout << c;
}
}
However this is not the case, the standard [stmt.ranged] (6.5.4) says that range-based-for works in one of 3 possibilities:
- The range is an array
- The range is a class with a callable
beginandendmethod - There is ADL reachable in an associated namespace (plus the
stdnamespace)
When I add begin and end functions for const char* in the global namespace I still get errors (from both VS12 and GCC 4.7).
Is there a way to get range-based-for loops to work with C style strings?
I tried adding an overload to namespace std and this worked but to my understanding it’s illegal to add overloads to namespace std (is this correct?)
If you write a trivial iterator for null-terminated strings, you can do this by calling a function on the pointer that returns a special range, instead of treating the pointer itself as the range.
And usage looks like this:
I don’t think this loses any expressiveness. Actually, I think this one is clearer.