简体   繁体   English

这在C ++ Primer 5版中似乎是错误的

[英]This seems to be an error in the book C++ Primer 5th edition

The following is an excerpt from the book C++ Primer 5th edition (emphasis is mine): 以下是C ++ Primer 5th Edition的摘录(重点是我的):

A nontype parameter may be an integral type, or a pointer or (lvalue) reference to an object or to a function type. 非类型参数可以是整数类型,也可以是对对象或函数类型的指针或(左值)引用。 An argument bound to a nontype integral parameter must be a constant expression. 绑定到非类型整数参数的参数必须是一个常量表达式。 Arguments bound to a pointer or reference nontype parameter must have static lifetime (Chapter 12, p. 450). 绑定到指针或引用非类型参数的参数必须具有静态生存期 (第12章,第450页)。 We may not use an ordinary (nonstatic) local object or a dynamic object as a template argument for reference or pointer nontype template parameters. 我们不能将普通(非静态)本地对象或动态对象用作引用或指针非类型模板参数的模板参数。 A pointer parameter can also be instantiated by nullptr or a zero-valued constant expression. 指针参数也可以由nullptr或零值常量表达式实例化。

Right below this paragraph one can find this highlighted Note: 在本段的正下方,可以找到此突出显示的注释:

Template arguments used for nontype template parameters must be constant expressions. 用于非类型模板参数的模板参数必须是常量表达式。

Maybe I'm missing something, but I believe the Note is wrong, as nontype template parameters of a pointer or lvalue reference to an object or function type are not constant expressions. 也许我遗漏了一些东西,但我相信Note是错误的,因为指向对象或函数类型的指针或左值引用的非类型模板参数不是常量表达式。

If you are worried about non-type pointer below you have perfectly valid specialization of a structure with non-type pointer to function template parameter: 如果您担心下面的非类型指针,则可以使用非类型指向函数模板参数的指针对结构进行完全有效的专业化处理:

void foo() { }

template <void(*)()>
struct bar { };

int main() {
   bar<&foo> b; 
}

The &foo here is also a constant expression as it has a static lifetime. 这里的&foo也是一个常量表达式,因为它具有静态寿命。

As Revolver_Ocelot mentioned 5.20[expr.const] /5 and 5.2 states it clearly: 正如Revolver_Ocelot提到的5.20 [expr.const] / 5和5.2明确指出:

A constant expression is either a glvalue core constant expression whose value refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value is an object where, for that object and its subobjects: 常量表达式可以是glvalue核心常量表达式,其值指向作为常量表达式允许的结果(定义如下)的实体,或者是prvalue核心常量表达式,其值是对象,对于该对象及其子对象,其中:

(...) (......)

  • if the object or subobject is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object (5.7), the address of a function, or a null pointer value 如果对象或子对象是指针类型,则它包含具有静态存储持续时间的对象的地址,该对象末尾的地址(5.7),函数的地址或空指针值

(I used draft N4296) (我使用了N4296草案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM