Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ passing unknown type to a virtual function

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

like image 838
Avner Gidron Avatar asked Sep 07 '17 06:09

Avner Gidron


Video Answer


1 Answers

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.

like image 116
StoryTeller - Unslander Monica Avatar answered Oct 11 '22 01:10

StoryTeller - Unslander Monica