Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forbid NULL value for function pointer parameter

Tags:

c++

I have a function:

void foo(int parm11, pointer to function) {…}

and I would like to forbid calling it with the NULL value for the second parameter. In other words I want to get an error message from the compiler at the following C++ source line:

foo(5, NULL);
like image 510
Alexander Abramov Avatar asked Feb 04 '18 21:02

Alexander Abramov


1 Answers

You can catch an explicit nullptr (and anything convertible to a null pointer constant), since it has its own type:

void foo(int, pfunc_type); // Your function
void foo(int, std::nullptr_t) = delete; // The "bad" overload

Of course, a determined user can still pass a null function pointer, they just can't do it by directly specifying a null pointer constant for the argument.

It may be preferable to reconsider pointers, and just take function references, as AlexD recommended.

like image 162
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 19:11

StoryTeller - Unslander Monica