I'm writing in C++ and I want to pass an unknown type (known only in run time) to a pure virtual function:
virtual void DoSomething(??? data);
where DoSomething
is an implementation of a pure virtual function in a derived class.
I planned to use templates but as it turn out virtual function and templates don't work together: Can a C++ class member function template be virtual?
I want to avoid using a base class for all the classes I pass to the function (something like object in C#).
Thanks in advance
You need type erasure. An example of this is the general purpose boost::any
(and std::any
in C++17).
virtual void DoSomething(boost::any const& data);
And then each sub-class can attempt the safe any_cast
in order to get the data it expects.
void DoSomething(boost::any const& data) {
auto p = any_cast<std::string>(&data);
if(p) {
// do something with the string pointer we extracted
}
}
You can of course roll out your own type erasing abstraction if the range of behaviors you seek is more constrained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With