为什么 NULL 不能是函数指针模板参数?
Why can't NULL be a function pointer template parameter?
当我试图在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]部分找到。
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 修改函数中的指针(将另一个指针作为参数传递)
- Clang bug?使用指针作为模板参数
- MSVC将仅移动结构参数解释为指针
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 如何使用非类型模板参数传入指向数组的指针
- 将成员函数指针作为参数传递给模板方法
- 匹配函数指针作为模板参数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 通过智能指针和转换对基本模板参数进行模板推导
- 为函数定义符号不明确的指针参数
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 将函数参数完美转发到函数指针:按值传递呢?
- 保留函数指针模板参数
- 如何构造一个以可变参数指针函数作为成员的类?
- 指向对象的非类型模板参数指针
- c++ 使用 *& as 参数(指针乐趣,三级树方法)