String literals not allowed as non type template parameters

前端 未结 5 1708
小鲜肉
小鲜肉 2020-11-30 02:11

The following quote is from C++ Templates by Addison Wesley. Could someone please help me understand in plain English/layman\'s terms its gist?

5条回答
  •  情书的邮戳
    2020-11-30 02:46

    It means you can't do this...

    #include 
    
    template 
    void f() { std::cout << P << '\n'; }
    
    int main()
    {
        f<"hello there">();
    }
    

    ...because "hello there" isn't 100% guaranteed to resolve to a single integral value that can be used to instantiate the template once (though most good linkers will attempt to fold all usages across linked objects and produce a new object with a single copy of the string).

    You can, however, use extern character arrays/pointers:

    ...
    extern const char p[];
    const char p[] = "hello";
    ...
        f

    (); ...

提交回复
热议问题