1

I have a method that has a void pointer as argument. In the body of the method I want to write some code that should execute only if the void pointer is convertible to a specific type of pointer(in my case it is a card*). How do I check if the card is convertible to card pointer?

  • Do you mean: you want to know if the pointer *actually points to* a `card` object ? In many cases you can convert a pointer but not then use the pointer after conversion. – M.M Apr 06 '16 at 01:20

1 Answers1

1

There is no C++ language feature to do this.

[Don't do this] One possible approach is to make the void* point to a class of a specific known type that stores type information and another void*. Then you can convert the first void* to the type-containing data type, determine if the type is what you want, and then take the nested void* and cast it to the desired type.

All that said, what's the real problem you're trying to solve? There's probably a C++-idiomatic approach to that.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • Including your own type information may be the only way to do this. If you need the `void*`, then you always have to assume you were given the right data type. http://stackoverflow.com/questions/4131091/dynamic-cast-from-void – Kyle A Apr 06 '16 at 01:23
  • While it is best to avoid `void*`, sometimes you need to use it to provide a hook. For example, when I write multi-threaded code, `pthread_create` expects a function pointer of type `void *(*func)(void*)`, because it can't know what types I may want to use. (Yes, I use pthreads, the compiler I have to use doesn't support c++11.) – Kyle A Apr 06 '16 at 01:32
  • @KyleA: That's because `pthreads` is C, not even C++98. In C++98, you can have `class Runnable { virtual void run() = 0; virtual ~Runnable();}`. – MSalters Apr 06 '16 at 09:34