简体   繁体   中英

Passing a member function of a class as pointer

Well this might be not the best solution to my problem so I will explain what I want to do.

I want to create a function which is a generic version of other classes (an interface in java way of seeing it). And then create a specialization of each class.

Later I want to create a vector of the generic class but each member of the vector is in reallity a casted member of the each specialized class. So when I call a function of each class in the vector call a diffrent function.

I tryied to do this using only inherence but, when I call the function of the vector call the implementation of the father and not it specialization.

I don't wnat to cast each member of the vector to call the right function because the hole point of doing this is to generalize a problem in the code. I mean make a dynamic behavor.

I also tryied to use pointers so the specialized class assign it function to a function pointer which is the one will be call. But this was not allowed because the pointer is namespace::classgeneralization::(int)(*f)(); and the function I want to point is namespace::classgeneralization::classspecialization::int f()(); so it do not compile.

I could may implemente the function out of the class and then point it in the class, but this is really ofuscate code I think. I also tryed to see if I could use a pointer to a lamda function but this is not posible at least in VS2010 as far I could research.

Maybe the hole perspective of solving the problem is wrong, and there is a way to do this properly and less ofuscate as I am trying. In any case I am open to other perspectives, so long I achive a vector of classes which each element is a different class with thiferent implementations of functions.

It's a bit difficult to understand your question, but it sounds to me that you are trying to achieve polymorphism in a very cumbersome way. Maybe the following code helps:

#include <iostream>
#include <vector>

class MyInterface
{
public:
   virtual void f() { std::cout << "MyInterface::f() called" << std::endl; }
};

class A : public MyInterface 
{
public:
   virtual void f() { std::cout << "A::f() called" << std::endl; }
};

class B : public MyInterface 
{
};

int main()
{
   std::vector<MyInterface*> objects;
   objects.push_back(new A);
   objects.push_back(new B);

   objects[0]->f();
   objects[1]->f();

   return 0;
}

This will output:

A::f() called
MyInterface::f() called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM