Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overloading a Function Based on shared_ptr Derived Class

There are a lot of SO questions which are similar to this, but I couldn't find precisely what I was looking for. I'm sorry if this is a duplicate.

I have a Parent class and two derived classes which inherit from it:

class Son : public Parent { ... };
class Daughter : public Parent { ... };

I then declare two shared_ptr to the Base class, and instantiate them with a shared_ptr to each of the derived classes:

shared_ptr<Parent> son = shared_ptr<Son>(new Son());
shared_ptr<Parent> daughter = shared_ptr<Daughter>(new Daughter());

Lastly, I would like to have a class which processes shared_ptr<Parent> based on which of the derived classes it points to. Can I use function overloading to achieve this effect is the question:

class Director {
public:
    void process(shared_ptr<Son> son);
    void process(shared_ptr<Daughter> daughter);
    ...
};

So I would like to be able to write the following code:

shared_ptr<Parent> son = shared_ptr<Son>(new Son());
shared_ptr<Parent> daughter = shared_ptr<Daughter>(new Daughter());
Director director;
director.process(son);
director.process(daughter);

Right now I'm having to do (which I would like to avoid):

director.process_son(boost::shared_polymorphic_downcast<Son>(son));
director.process_daughter(boost::shared_polymorphic_downcast<Daughter>(daughter));
like image 905
Alan Turing Avatar asked May 30 '11 23:05

Alan Turing


1 Answers

It isn't possible to overload like that, you would need a switch statement to achieve something similar with dispatch within one method on Director.

Maybe you should move the process() method to the Parent class (and override it in Son and Daughter), that way you can use normal virtual function resolution to call the right one.

like image 121
James Avatar answered Sep 28 '22 07:09

James