Inconsistency between std::string and string literals

后端 未结 6 1457
耶瑟儿~
耶瑟儿~ 2020-12-28 12:30

I have discovered a disturbing inconsistency between std::string and string literals in C++0x:

#include 
#include          


        
6条回答
  •  粉色の甜心
    2020-12-28 13:00

    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")) ...
    

提交回复
热议问题