I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated.
In this example, I would like the output to be "1"
class A {
public:
int f();
int (*x)();
}
int A::f() {
return 1;
}
int main() {
A a;
a.x = a.f;
printf("%d\n",a.x())
}
But this fails at compiling. Why?
This question is related to
c++
oop
function-pointers
You need to use a pointer to a member function, not just a pointer to a function.
class A {
int f() { return 1; }
public:
int (A::*x)();
A() : x(&A::f) {}
};
int main() {
A a;
std::cout << (a.*a.x)();
return 0;
}
Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs&&... rargs) = 0;
//virtual RET call() = 0;
};
template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
T * owner;
RET(T::*x)(RArgs...);
RET call(RArgs&&... rargs) {
return (*owner.*(x))(std::forward<RArgs>(rargs)...);
};
CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};
template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
T* owner;
RET(T::*x)(Args...);
RET call() {
return (*owner.*(x))(std::get<Args&&>(args)...);
};
std::tuple<Args&&...> args;
CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};
Test / example:
class container {
public:
static void printFrom(container* c) { c->print(); };
container(int data) : data(data) {};
~container() {};
void print() { printf("%d\n", data); };
void printTo(FILE* f) { fprintf(f, "%d\n", data); };
void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
int data;
};
int main() {
container c1(1), c2(20);
CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
Callback_t<void>* fp1 = &f1;
fp1->call();//1
CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
Callback_t<void>* fp2 = &f2;
fp2->call();//20
CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
Callback_t<void, int>* fp3 = &f3;
fp3->call(15);//20:15
}
Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.
Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....
Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.
#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs... rargs) = 0;
virtual ~Callback_t() = default;
};
template<class RET, class... RArgs> class CallbackFactory {
private:
template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
private:
T * owner;
RET(T::*x)(CArgs..., RArgs...);
std::tuple<CArgs...> cargs;
RET call(RArgs... rargs) {
return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
};
public:
Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
~Callback() {};
};
public:
template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}
While this is based on the sterling answers elsewhere on this page, I had a use case which wasn't completely solved by them; for a vector of pointers to functions do the following:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
class A{
public:
typedef vector<int> (A::*AFunc)(int I1,int I2);
vector<AFunc> FuncList;
inline int Subtract(int I1,int I2){return I1-I2;};
inline int Add(int I1,int I2){return I1+I2;};
...
void Populate();
void ExecuteAll();
};
void A::Populate(){
FuncList.push_back(&A::Subtract);
FuncList.push_back(&A::Add);
...
}
void A::ExecuteAll(){
int In1=1,In2=2,Out=0;
for(size_t FuncId=0;FuncId<FuncList.size();FuncId++){
Out=(this->*FuncList[FuncId])(In1,In2);
printf("Function %ld output %d\n",FuncId,Out);
}
}
int main(){
A Demo;
Demo.Populate();
Demo.ExecuteAll();
return 0;
}
Something like this is useful if you are writing a command interpreter with indexed functions that need to be married up with parameter syntax and help tips etc. Possibly also useful in menus.
Call member function on string command
#include <iostream>
#include <string>
class A
{
public:
void call();
private:
void printH();
void command(std::string a, std::string b, void (A::*func)());
};
void A::printH()
{
std::cout<< "H\n";
}
void A::call()
{
command("a","a", &A::printH);
}
void A::command(std::string a, std::string b, void (A::*func)())
{
if(a == b)
{
(this->*func)();
}
}
int main()
{
A a;
a.call();
return 0;
}
Pay attention to (this->*func)();
and the way to declare the function pointer with class name void (A::*func)()
While you unfortunately cannot convert an existing member function pointer to a plain function pointer, you can create an adapter function template in a fairly straightforward way that wraps a member function pointer known at compile-time in a normal function like this:
template <class Type>
struct member_function;
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...)>
{
template <Ret(Type::*Func)(Args...)>
static Ret adapter(Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...) const>
{
template <Ret(Type::*Func)(Args...) const>
static Ret adapter(const Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
int (*func)(A&) = &member_function<decltype(&A::f)>::adapter<&A::f>;
Note that in order to call the member function, an instance of A
must be provided.
int (*x)()
is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;
.
Source: Stackoverflow.com