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

Why can't NULL be a function pointer template parameter?

本文关键字:参数 指针 函数 NULL 不能 为什么      更新时间:2023-10-16

当我试图在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.notype]部分找到。