a.lasram
a.lasram

Reputation: 4411

local variable as a non-typename argument

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

For example, in the next code local_var cannot be argument to X.

template<int& x> struct X {};

void f(int local_var)
{
    X<local_var> x;
}

Upvotes: 6

Views: 524

Answers (2)

Pixelchemist
Pixelchemist

Reputation: 24936

The "value" of a template needs to be present at compile time.

template<int x> struct X {};

Even if you do not bind a reference or pass a pointer here, the compiler must know the value of the passed elements at compile time.

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

  • The "value" of a reference is a reference (implementation dependent actually a pointer in most of them)
    • The address of the object must be known at compile time
  • The "value" of a pointer template<int*> is an address...
    • ... which in turn must be known here, too, of course.
  • The "value" of a value-type is the value itself which also must 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 to (in addition to Andy's answer) prevent any conclusions that would suggest to use a value type instead of a reference.

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126432

Because template arguments must be evaluated at compile time, and the compiler won't know the address of a local variable until run-time (in order to bind a reference to an object, the compiler needs to know the address of that object).

Notice, that the C++11 Standard tells exactly what non-type template arguments can be provided in paragraph 14.3.2/1:

A template-argument for a non-type, non-template template-parameter shall be one of:

— for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

— the name of a non-type template-parameter; or

— a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

— a constant expression that evaluates to a null pointer value (4.10); or

— a constant expression that evaluates to a null member pointer value (4.11); or

— a pointer to member expressed as described in 5.3.1; or

— an address constant expression of type std::nullptr_t.

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

Upvotes: 6

Related Questions