Let's say that I have a function which takes in pointers.
int functionA(int* a, int* b)
{
...
}
I can add null checks inside functionA. Is there a way that I can ensure that an error occurs on the compile time whenever nullptr
is passed as a parameter.
Is there a way that I can ensure that an error occurs on the compile time whenever nullptr is passed as a parameter.
If you specifically mean the nullptr
keyword, then sort of. You can provide overloads that would be chosen in that case, and define them deleted. This works as long as you don't explicitly bypass the overloading by casting for example.
int functionA(int*, std::nullptr_t) = delete;
int functionA(std::nullptr_t, int*) = delete;
// ...
functionA(&i, &j) // OK
functionA(nullptr, &i); // error
functionA(&i, nullptr); // error
functionA(nullptr, nullptr); // error
or
NULL
This will require adding overloads for integers in addition to the previous overloads:
int functionA(int*, int) = delete;
int functionA(int, int*) = delete;
// ...
functionA(NULL, &i); // error
functionA(&i, NULL); // error
functionA(NULL, NULL); // error
If you mean any pointer with null value, then that cannot be done because the values of function arguments cannot generally be known at compile time.
If your goal is to not use the pointers as iterators, then it would be safer and more convenient to pass references instead.