If the argument is meant to be opaque to the client, you might expose it as a handle type that does not implicitly convert, e.g.
#include <cstdint>
using api_handle = std::uintptr_t;
inline api_handle make_api_handle(const char* p)
{
return (api_handle)(const void*)p;
}
inline api_handle make_api_handle(const int* p)
{
return (api_handle)(const void*)p;
}
The two-stage conversion is because the language standard technically only says that round-trip conversions between any object pointer and void*
are safe, and that round-trip conversions between void*
and uintptr_t
or intptr_t
are safe. Within your library, you can do the conversion the opposite way to retrieve the original pointer.
That somewhat-contrived example lets you convert specific types of pointers to handles explicitly, but pointers do not convert to handles implicitly. (Although, now, integral values will implicitly convert to handles, and give you undefined behavior.) In the real world, the helper functions should be optimized out.
If this kind of approach works for your API, another solution would be to wrap your void*
in a minimal struct
and pass those around. Modern compilers should be able to pass them around in registers, just like pointers. You might also add a field storing type or other information. Another option might be to keep a vector of valid objects and pass around indices to that, like file handles in Unix.
For constructors, you can use the explicit
keyword to disable all implicit conversion on the arguments.
void*
for pointers to a certain class?" - No, there is not. All pointers are implicitly convertible tovoid*
, that is a core feature of the C++ language. I would probably wrap the API function in question and make the wrapper only accept pointers of the correct type, and then pass them along to the API as needed.void*
to other pointer types. That is the opposite of this question