Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 846
a.lasram Avatar asked Jun 27 '13 23:06

a.lasram


People also ask

What are non-type parameters?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

Which parameter is allowed for non-type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.

Why do we use Typename in C++?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.


1 Answers

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.

like image 184
Andy Prowl Avatar answered Oct 03 '22 13:10

Andy Prowl