Reputation: 358
because of specific reasons I want a function pointer that can point to any member function of the class and can be changed whenever I want. I thought of a setup like the following:
//#include <iostream>
//#include <functional>
#include <cstdarg>
class someclass{
public:
someclass(){ func = trial; }
template<typename T, typename... Args> void setfunc(T t, Args... args){
func = t(args...);
}
void trial(){
//do some stuff
}
void trying(int i){
//do other stuff
}
template <typename T>void (someclass::*func)(Args...);
};
int main(){
someclass c;
(c.*(c.func))();
c.setfunc(someclass::trying, 32);
(c.*(c.func))();
}
Unfortunately C++ doesn't let me do that and instead gives me the error:
data member 'func' cannot be a member template
I read that you can't make templates of member variables and when I write
void (someclass::*func)();
and scram the Args
-part in setfunc()
, it works just fine for trial()
, but not for trying()
. So my question is: is there anyway to fix this, work around it or any other way I can try?
Temporarily I'm here:
#include <iostream>
#include <functional>
class someclass{
public:
someclass(){
func = std::bind(&someclass::trial, std::placeholders::_1);
}
void setfunc(std::function<void(someclass&)> f){ func = f; }
void trial(){
//do some stuff
//std::cout << "1" << std::endl;
}
void trying(int i){
//do other stuff
//std::cout << "2" << std::endl;
}
std::function<void(someclass&)> func;
};
int main(){
someclass c;
#c.func(); //!!!
c.setfunc(std::bind(&someclass::trying, std::placeholders::_1, 32));
#c.func(c); //!!!
}
My IDE marks the lines with the #
Upvotes: 0
Views: 119
Reputation: 218343
You may use std::function
, something like
class someclass{
public:
someclass(){ func = &someclass::trial; }
void setfunc(std::function<void(someclass&)> f){ func = f; }
void trial(){
//do some stuff
}
void trying(int i){
//do other stuff
}
std::function<void(someclass&)> func;
};
int main(){
someclass c;
c.func(c);
c.setfunc([](someclass& cl){cl.trying(32);});
c.func(c);
}
Upvotes: 1