局部变量作为非类型名称参数 [英] local variable as a non-typename argument

查看:103
本文介绍了局部变量作为非类型名称参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用局部变量作为非类型参数是非法的?

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

例如,在下一个代码中 local_var 不能作为 X 的参数。

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;
}


推荐答案

因为必须评估模板参数在编译时,编译器直到运行时才知道局部变量的地址(为了将引用绑定到对象,编译器需要知道该对象的地址)。

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).

请注意,C ++ 11标准准确说明了在14.3.2 / 1段中可以提供哪些非类型模板参数:

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

用于非类型,非模板 template-parameter template-argument 应为:

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

-对于整数或枚举类型的非类型 template-parameter ,是类型的转换后的常量表达式
(5.19)模板参数
;

— 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

-一个常数表达式(5.19),用于指定具有静态存储持续时间和
外部或内部链接或具有外部或内部链接的函数的对象的地址链接,包括函数模板
和函数 template-ids ,但不包括非静态类成员,表示为(忽略括号)为
& id-expression ,但&如果名称指向函数或数组,则可以省略;如果相应的模板参数为引用,则可以省略

— 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

—一个常量表达式,其值为空指针值(4.10);

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

—一个常量表达式,其值为空成员指针值(4.11);或者

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

-指向成员的指针,如5.3.1所述;或

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

-类型为 std :: nullptr_t 的地址常量表达式。

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

如您所见,局部变量不在此列表中。

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

这篇关于局部变量作为非类型名称参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆