c++ - 如何检查函数指针是否存在

标签 c++ exception pointers exception-handling function-pointers

在 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 是可以的。但是不可能将指针传递给一开始就不存在的函数。所以你不必担心这个。尽管可以只声明一个函数而不定义它并传递它的地址。在这种情况下,您将收到链接器错误。

关于c++ - 如何检查函数指针是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23395388/

相关文章:

C++ 函数 : Number of memory access

java - try,catch,finally的执行顺序是什么

pointers - "cannot take the address of"和 "cannot call pointer method on"

c - C 中的二维初始化语法

c++ - C++ 中的内联函数

c++ - 将迭代器返回到 C 数组的方法的正确类型声明

c++ - 是否可以将 PEX 与 C 一起使用?

c++ - 读取文件抛出异常

java - 使用 JDBC 和 MySQL 添加行有问题吗?

c++ - 类方法指向其他类的其他方法