Restrict passed parameter to a string literal

前端 未结 6 1179
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 23:20

I have a class to wrap string literals and calculate the size at compile time.

The constructor looks like this:

template< std::size_t N >
Liter         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 23:24

    A string literal does not have a separate type to distinguish it from a const char array.

    This, however, will make it slightly harder to accidentally pass (non-const) char arrays.

    #include 
    
    struct Literal
    {
        template< std::size_t N >
        Literal( const char (&literal)[N] ){}
    
        template< std::size_t N >
        Literal( char (&literal)[N] ) = delete;
    };
    
    int main()
    {
        Literal greet( "Hello World!" );
        char a[] = "Hello world";
        Literal broke(a); //fails
    }
    

    As to runtime checking, the only problem with a non-literal is that it may not be null-terminated? As you know the size of the array, you can loop over it (preferable backwards) to see if there's a \0 in it.

提交回复
热议问题