Restrict passed parameter to a string literal

前端 未结 6 1182
没有蜡笔的小新
没有蜡笔的小新 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:33

    Yes. You can generate compile time error with following preprocessor:

    #define IS_STRING_LITERAL(X) "" X ""
    

    If you try to pass anything other than a string literal, the compilation will fail. Usage:

    Literal greet(IS_STRING_LITERAL("Hello World!"));  // ok
    Literal greet(IS_STRING_LITERAL(broke)); // error
    

提交回复
热议问题