为什么不允许使用0作为void *的默认非类型模板参数 [英] Why using 0 as default non type template parameter for void* is not allowed

查看:159
本文介绍了为什么不允许使用0作为void *的默认非类型模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码无法编译?即使 void * ptr = 0是合法的;

Why does the following code fail to compile? Even though it is legal to do void* ptr = 0;

template <void* ptr = 0>
void func();

int main() {
    func();
    return 0;
}

我之所以问,是因为我发现一个非常受信任的来源做了类似的事情并且失败了可以在我的机器上编译

I ask because I found that a very trusted source did something similar and it failed to compile on my machine

注意应该将编译器错误和我的问题一起发布,所以在这里

NOTE Should have posted the compiler error along with my question so here it is

so_test.cpp:1:23: error: null non-type template argument must be cast to template parameter type 'void *'
template <void* ptr = 0>
                      ^
                      static_cast<void *>( )
so_test.cpp:1:17: note: template parameter is declared here
template <void* ptr = 0>
                ^
so_test.cpp:5:5: error: no matching function for call to 'func'
    func();
    ^~~~
so_test.cpp:2:6: note: candidate template ignored: substitution failure [with ptr = nullptr]: null non-type template argument must be cast to template parameter type 'void *'
void func();
     ^


推荐答案

<$类型的模板参数不允许使用c $ c> 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.

这篇关于为什么不允许使用0作为void *的默认非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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