且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不允许使用0作为void *的默认非类型模板参数

更新时间:2023-11-14 23:53:04

void * 。请参阅标准中的[temp.param] / 4,该摘要也总结在 http: //en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter

Template parameters of type void* are not allowed. See [temp.param]/4 in the standard, also summarized at http://en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter


非类型 template-parameter 必须具有以下类型之一(可选的 cv限定)类型:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:


  • 整数或枚举类型,

  • 指向对象或函数的指针,

  • 对对象的左值引用或对函数的左值引用,

  • 指向成员的指针,

  • std :: nullptr_t

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.

由于 void 不是对象或函数类型,因此 void * 不在允许的类型中。

Since void is not an object or function type, void* is not among the permitted types.

附录: A void *在编译时知道的值不是很有用。由于常量表达式不允许 reinterpret_cast ,因此无法在编译时检查其值;在编译时,对于某些对象类型 T ,也无法将其转换为 T *

Addendum: A void* value known at compile time wouldn't be very useful. It's not possible to examine its value at compile time since reinterpret_cast is not allowed in constant expressions; nor is it possible to convert it to T* for some object type T at compile time.