Some const char * are unavailable at compile time?

前端 未结 2 1645
离开以前
离开以前 2021-01-03 23:16

Let\'s suppose we have a template function with non-type parameter of const char * like this:

template  void print()         


        
2条回答
  •  天涯浪人
    2021-01-03 23:46

    The instantiation variable of a template needed to have external linkage, and const was implicitly internal linkage. So you have to write:

    extern char const constMessage[] = "Const message";
    

    (Another alternative would be for it to be a static class member. Static class members always have external linkage.)

    The case of string literals is in some ways similar: their type is char const[]. But it's even worse: template instantiations (at least the early ones) need a name, and a string literal doesn't have one. Even more to the point, it's unspecified whether identical string literals are the same object or not, so in the following:

    template 
    struct Toto { char const* f() const; };
    
    Toto <"titi"> t1;
    Toto <"titi"> t2;
    

    it would be unspecified whether t1 and t2 had the same type or not.

提交回复
热议问题