gpt4 book ai didi

c++ - 作为非类型名参数的局部变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:40 26 4
gpt4 key购买 nike

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

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

template<int& x> struct X {};

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

最佳答案

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

请注意,C++11 标准在第 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.

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

关于c++ - 作为非类型名参数的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com