Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast a function with a derived argument to a function with a base argument?

Tags:

c++

c++11

I have a class named Reciever that has a function called recieve(const Event *), where Event inherits from BaseEvent. I want to create a bind to a specific instance of that class. The instance is called rec. To do this I use:

void(Reciever::*func)(const Event *) = &Reciever::recieve;
auto recievePtr = std::bind(func, &rec, std::placeholders::_1);

However, when I try to store this in a vector, I have to specify an std::function that takes a BaseEvent as the input, not an Event, like so:

std::vector<std::function<void(const BaseEvent*)>>

How can I cast recievePtr so I can store it properly in the vector? Is this even possible? The issue with using a function pointer to a BaseEvent is that the Reciever can have multiple recieve() methods with different derived classes all based on BaseEvent

like image 377
user975989 Avatar asked Jul 15 '15 02:07

user975989


People also ask

How do you call a derived function from base class?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

What happens if the base class and derived class?

Base class object will call base class function and derived class object will call derived class function.

What will happen if the base class and the derived class define a function with the same name?

38. What happens if the base and derived class contains definition of a function with same prototype? A. Compiler reports an error on compilation.

Can a base class call a member function of a derived class?

You cannot call a derived virtual method from inside of a base class constructor/destructor. The VMT does not contain a pointer to the derived class method table at those stages. Save this answer. Show activity on this post.


1 Answers

You can try something along the following. This compiled and ran fine on my machine. Visual Studio targeting platform toolset v120.

Reciever rec;

std::vector<std::function<void(const BaseEvent*)>> vector;

vector.push_back(
    [&rec](const BaseEvent* event)
{
    rec.recieve(static_cast<const Event*>(event));
});

vector.push_back(
    [&rec](const BaseEvent* event)
{
    rec.recieve(static_cast<const EventD*>(event));
});

const BaseEvent* e = new Event();
const BaseEvent* d = new EventD();

vector[0](e);
vector[1](d);
like image 114
Taekahn Avatar answered Sep 29 '22 18:09

Taekahn