Const as a parameter of a non-piggy template (VARIABLE cannot appear in a constant expression)

Why does this work?

char __nontype[] = "foo"; typedef TemplateClass<T, __nontype> MyClass; 

But is this (with a constant variable) not?

 const char __nontype[] = "foo"; typedef TemplateClass<T, __nontype> MyClass; 

Compiler Error:

error: '__nontype cannot appear in constant expression

error: template argument 2 is not valid

+7
source share
2 answers

The difference is that const affects communication. It works if you add extern . However, as far as I can tell:

14.3.2 Argument template non-type [temp.arg.nontype]

The template argument for a non-piggy template without template must be one of the following:

  • an integral constant expression (including a literal type constant expression that can be used as an integral constant expression, as described in 5.19); or
  • asymmetric pattern name; or
  • constant expression (5.19), which denotes the address of an object with a static storage duration and external or internal communication or a function with external or internal communication, including function templates and identifiers of function templates, but excluding non-static class members, expressed (ignoring brackets) as well as id- an expression, except that it can be omitted if the name refers to a function or array and should be omitted if the corresponding parameter template is a link; or
  • constant expression that evaluates the value of the null pointer (4.10); or
  • constant expression that evaluates the value of the pointer of the zero element (4.11); or
  • pointer to an element expressed as described in 5.3.1.

It should also work without extern . An object is allowed to have an internal link, but your compiler does not yet support this. This is one of the changes in C ++ 11; the previous C ++ standard did not allow this.

+5
source

The error says this: the result is not a constant expression (it is known at the time of communication, but not compilation time).

Here is an example that will work:

 typedef const char *nontype_t; template <nontype_t> struct Y {}; char hello[] = "hello"; constexpr char* world = hello; int main() { Y<hello> a; } 
+1
source

All Articles