There are four classes.
Base, Derived1, Derived2, BaseUser.
Derived1 and Derived2 inherits Base class.
The final purpose is using functions of Derived1 and Derived2 on BaseUser codes through virtual function in Base class. (I'm implementing api server, and i want to set different api functions depending on certain condition.)
//base_user.h
BaseUser::SetBase(Base* base);
//other cc file
BaseUser user;
Derived1 dev1;
Derived2 dev2;
condition ? user.SetBase(&dev1) : user.SetBase(&dev2);
By the way, There is an typedef-ed funciton pointer on base.cc source code.
(It doesn't matter for me whether the type definition is in the class or outside the class.)
I'll call the type as func_ptr from now on.
public:
typedef int(*func_ptr)(int v1, int v2, int v3);
Also Base class has a vector of the type as a member.
protected:
std::vector<std::pair<int, func_ptr>> functions;
I want to use the functions in Deriveds by inserting the functions of them into vector functions
.
if I define
int func1(int v1, int v2, int v3);
in any Derived class, and try
functions.push_back(std::pair<int, func_ptr>(1, &Derived::func1));
it shows the message that says the argument types are different each othe. such like below
no instance of constructor "int, func_ptr" matches -- argument type int (Derived::*)(int v1, int v2, int v3)
I think it is not a problem only on std::pair. It seems like the types of func_ptr and func1 are different each other because the function func1 is defined in the Derived class.
How can I implement it?
virtual code (not tested)
//Base.h
class Base{
public:
typedef int(*func_ptr)(int v1, int v2, int v3);
//...//
protected:
std::vector<std::pair<int, func_ptr>> functions;
virtual void InitializeFunctionPointers();
}
//Derived1.h
class Derived1{
int func1(int v1, int v2, int v3);
int func2(int v1, int v2, int v3);
void InitializeFunctionPointers() override;
//...//
public:
Derived1();
}
//Derived1.cc
//...//
void Derived1::InitializeFunctionPointers(){
functions.push_back(std::pair<int, func_ptr>(1, &Derived1::func1));
//...//
}