Differentiate String Literal from Char Array

后端 未结 3 787
花落未央
花落未央 2020-12-16 10:55

I want to write some function that takes a string literal - and only a string literal:

template 
void foo(const char (&s         


        
3条回答
  •  天涯浪人
    2020-12-16 11:25

    Depending on what exactly you want, this may or may not work for you:

    #include 
    
    template 
    void foo(const char (&str)[N]) {}
    
    template  struct check_literal {};
    
    #define foo(arg) foo((check_literal(),arg))    
    
    int main()
    {
    
        // This compiles
        foo("abc");
    
        // This does not
        static const char abc[] = "abc";
        foo(abc);
    }
    

    This works with g++ and clang++ in -std=c++11 mode only.

提交回复
热议问题