gpt4 book ai didi

c++ - 为什么 NULL 不能是函数指针模板参数?

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:44 24 4
gpt4 key购买 nike

当我尝试在 GCC 或 clang 中编译它时,出现错误。

#include <cstddef>

template <void (*Function)()>
void Wrapper()
{
}

int main()
{
void (*meow)() = Wrapper<NULL>;
return meow ? 1 : 0;
}
$ g++ -m64 -std=c++11 -c nulltemplate.cpp
nulltemplate.cpp: In function ‘int main()’:
nulltemplate.cpp:10:19: error: no matches converting function ‘Wrapper’ to type ‘void (*)()’
nulltemplate.cpp:4:6: error: candidate is: template<void (* Function)()> void Wrapper()

为什么我不能这样做?错误的措辞就好像 Wrapper 是一个无法根据上下文解析为特定函数指针类型的重载,这对我来说没有意义。

最佳答案

NULL是一个宏,可以定义为(在您的系统上似乎确实如此):

#define NULL 0

它的类型是 int .所以你的代码正在做 Wrapper<0>

但是,对于作为函数指针的非类型模板参数,您必须传递一个实际的函数指示符或一个空指针值。不考虑从整数到指针的隐式转换。 0是一个空指针常量,但不是一个空指针值

引入 C++11 nullptr避免这种问题; nullptr不能与整数混淆。

非类型模板参数的完整条件列表,以及考虑转换的列表,可以在 C++ 标准的 [temp.arg.nontype] 部分找到。

关于c++ - 为什么 NULL 不能是函数指针模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793581/

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