Local variable as non-typename argument

Why is it not allowed to use a local variable as a non-type argument?

For example, in the following code, local_var cannot be an argument of X

 template<int& x> struct X {}; void f(int local_var) { X<local_var> x; } 
+6
source share
2 answers

Since the template arguments must be evaluated at compile time, and the compiler will not know the address of the local variable until run time (to bind a link to an object, the compiler must know the address of this object).

Note that the C ++ 11 standard specifies exactly which non-piggy type template arguments can be provided in paragraph 14.3.2 / 1:

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

- for a non-standard template parameter of an integral or enumerated type, the transformed constant expression (5.19) of the template parameter type; or

- name of the asymmetric pattern; or

- constant expression (5.19), which denotes the address of an object with a static storage time and external or internal communication or a function with external or internal communication, including functional templates and function template functions, but excluding non-static class members expressed (ignoring parentheses) as and id-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

- a constant expression that calculates the value of the null pointer (4.10); or

- a constant expression that calculates the value of the pointer of the zero element (4.11); or

- a pointer to an element expressed as described in 5.3.1; or

- expression of an address constant of the type std::nullptr_t .

As you can see, local variables are not on this list.

+6
source

The "value" of the template must be present at compile time.

 template<int x> struct X {}; 

Even if you don’t bind the link or pass a pointer here, the compiler must know the value of the elements passed at compile time.

Replacing int &x with int x is entirely here. Material about int & answered correctly. I just wanted to point out that it applies to all non-typed template arguments.

  • The "value" of a link is a link (in most cases, the dependency depends on the pointer)
    • The address of the object must be known at compile time
  • The "value" of the template<int*> pointer is the address ...
    • ... which, in turn, should also be known here.
  • A "value" of type value is the value itself, which must also be known at compile time

 X<local_var> x; // will not work, local_var does not exist at compile time X<1> x; // works since 1 is known 

I just wanted (in addition to Andy's answers) to prevent any conclusions that would suggest using a value type instead of a reference.

0
source

Source: https://habr.com/ru/post/948279/


All Articles