如何检查函数指针是否存在
How to check a function pointer exists
在C++中,我试图编写一个带有函数指针的函数。如果为不存在的函数传递函数指针,我希望能够抛出异常。我试着像处理普通指针一样处理函数指针,并检查它是否为空
#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (funcPtr != NULL) {
return funcPtr(x);
} else {
throw "not a valid function pointer";
}
}
int main(int argc, char** argv) {
try {
int x = 5;
cout << "add_1 result is " << add_1(x) << endl;
cout << "foo add_1 result is " << foo(x, add_1) << endl;
cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
cerr << "Error: " << strException << endl;
}
catch (...) {
cerr << "We caught an exception of an undetermined type" << endl;
}
return 0;
}
但这似乎不起作用。最好的方法是什么?
检查NULL是可以的。但不可能将指针传递给一个一开始就不存在的函数。所以你不必担心这个。虽然可以只声明一个函数而不定义它并传递它的地址。在这种情况下,你会得到链接器错误。
如果你传递的指针不存在,它会自动抛出一个错误,如果你声明一个指针,那么你必须用null初始化它以避免垃圾值,所以与null进行比较没有任何作用。
如果你仍然想检查,然后尝试分配一些函数(如add、sub等(,如果需要,则ok,如果不需要,则会再次显示前面提到的错误。
#include<cstddef>
#include <iostream>
using namespace std;
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (*funcPtr != NULL) {
return funcPtr(x);
}
else
{
cout << "not a valid function pointer";
}
}
如果您想"抛出"异常,那么您也需要"捕获"它。简而言之,您的代码失败的原因有两个:,1( 您没有检查函数指针的值。2( 您没有正确捕获抛出的异常。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针