I have discovered a disturbing inconsistency between std::string
and string literals in C++0x:
#include
#include
According to N3290 6.5.4, if the range is an array, boundary values are
initialized automatically without begin
/end
function dispatch.
So, how about preparing some wrapper like the following?
struct literal_t {
char const *b, *e;
literal_t( char const* b, char const* e ) : b( b ), e( e ) {}
char const* begin() const { return b; }
char const* end () const { return e; }
};
template< int N >
literal_t literal( char const (&a)[N] ) {
return literal_t( a, a + N - 1 );
};
Then the following code will be valid:
for (auto e : literal("hello")) ...
If your compiler provides user-defined literal, it might help to abbreviate:
literal operator"" _l( char const* p, std::size_t l ) {
return literal_t( p, p + l ); // l excludes '\0'
}
for (auto e : "hello"_l) ...
EDIT: The following will have smaller overhead (user-defined literal won't be available though).
template< size_t N >
char const (&literal( char const (&x)[ N ] ))[ N - 1 ] {
return (char const(&)[ N - 1 ]) x;
}
for (auto e : literal("hello")) ...