I'm using an API that accepts void*
in certain functions. I frequently accidentally pass the wrong pointer type to the function, and of course it compiles fine, but doesn't work at runtime.
Is there a way to disable implicit conversion to void*
for pointers to a certain class?
You can add a deleted overload for the API function:
// API function
void api(void* p) {
// ...
}
// Special case for nullptr
inline void api(std::nullptr_t) {
api((void*)nullptr);
}
// Everything else is disabled
template <class ...T>
void api(T&&... t) = delete;
int main() {
int i = 0;
void* p = &i;
api(p); // Compiles
// api(&i); // Doesn't compile
}