gpt4 book ai didi

c++ - 为什么vc++ 2019不接受代码?

转载 作者:太空狗 更新时间:2023-10-29 19:55:58 25 4
gpt4 key购买 nike

template<int N>
void f()
{
constexpr int n = 9;
++*const_cast<int*>(&n); // ok
++*const_cast<int*>(&N); // error C2101: '&' on constant
}

int main()
{
f<8>();
}

根据 cppref :

the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

两个问题:

<强>1。为什么vc++ 2019 (with/std:c++latest) 不接受代码?

<强>2。为什么 C++20 允许模板参数对象是左值?

最佳答案

模板参数对象是一个规范术语,仅指具有类类型的模板参数。

temp.param/6 (emphasis mine)

...An id-expression naming a non-type template-parameter of class type T denotes a static storage duration object of type const T, known as a template parameter object, whose value is that of the corresponding template argument after it has been converted to the type of the template-parameter. All such template parameters in the program of the same type with the same value denote the same template parameter object. [ Note: If an id-expression names a non-type non-reference template-parameter, then it is a prvalue if it has non-class type. Otherwise, if it is of class type T, it is an lvalue and has type const T ([expr.prim.id.unqual]). — end note ]

由于 int 不是类类型,它不是模板参数对象。我们可以在这里查阅有关值类别的规范文本的相关部分,它支持注释:

expr.prim.id.unqual/2

... The expression is an lvalue if the entity is a function, variable, structured binding ([dcl.struct.bind]), data member, or template parameter object and a prvalue otherwise ...

由于我们不是在“模板参数对象”的情况下,我们正在处理纯右值,因此可能不会像任何其他纯右值一样对其应用一元 &

关于c++ - 为什么vc++ 2019不接受代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285364/

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