Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a function pointer exists

In C++, I'm trying to write a function with function pointers. I want to be able to throw an exception if a function pointer is passed for a function that does not exist. I tried to handle the function pointer like a normal pointer and check if it is null

#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;
}

but that doesn't seem to work. What is the best way to do this?

like image 878
John Avatar asked Sep 30 '22 22:09

John


1 Answers

Checking for NULL is ok. But it is not possible to pass a pointer to a function that does not exist in the first place. So you don't have to worry about this. Although it is possible to just declare a function without defining it and pass the address of it. In that case you will get linker error.

like image 127
Rakib Avatar answered Oct 03 '22 15:10

Rakib