If I have a generic function that takes a void* as a parameter, can Auto in C++11 help stop any bad casting of that parameter?
For instance, we may have an event system that sends events and a pointer to some data that is relevant for the event it sends.
void EventClass::SendEvent (eventTypeEnum eventType, void* eventData)
{
int* castEventData = static_cast<int*> (eventData);
//.. Do something
}
In the above example, one eventType could be sent with eventData as a float* and another as a pointer to a structure.
The static_cast there will be mis-casting and causing problems.
Is there a way auto could be used to avoid this issue.
Please note, this is just an example (not a great one though sorry) to help me understand the possibilities of auto and not an actual issue I have.
4
No, remember that ‘auto’ is a compile time feature: it says the compiler may infer the type of a variable from it’s initializer. For example, if the compiler sees
auto i = 10;
it can infer that i
is an integer. Or more usefully, given
auto it = c.begin();
where c
is some sort of collection, the compiler can infer that it
is an iterator of the appropriate subtype.
Here your function simply says that eventData is a void*, so that’s all the compiler has to go on. Detecting that in a particular instance you’ve passed a float* rather than an int* is a run time issue and auto won’t solve it.
I think some languages have used an ‘auto’ for a generic data type like Microsoft’s ‘Variant’, but that’s not what the ‘auto’ in C++ is providing.
It sounds like you need support for Run Time Type Identification (RTTI), but that still assumes some constraint on what you are passing in the function. If you truly need to be able to pass anything from a char* to a IncrediblyComplexStruct*, you probably are just going to have to pass the type along with the value, possibly using the eventTypeEnum as @RobertHarvey suggested.
1