I have recently declared similar class to this:
class Foo {
public:
void run();
private:
void foo();
void boo();
void doo();
std::function<void()>getFunction(int);
};
In this example I'd like to get pointer to the member function depending on the passed integer.
void Foo::run(){
std::function<void()> f;
for(int i = 0; i < 3; i++){
f = getFunction(i);
f();
}
}
std::function<void()>Foo::getFunction(int i){
switch(i){
case 0: return foo;
case 1: return Foo::boo;
case 2: return this->*doo;
}
}
All cases cause compiler errors. Adding static
to function for case 1
works but I prefer not to use static members.
Is there any way to get these pointers properly without using static
keyword?
As an extension to songyuanyao's answer
What about using lambdas? (assuming it's only a matter of being able to call the internal functions and not the function pointers by themselves that are important)
void Foo::run(){
std::function<void()> f;
for(int i = 0; i < 3; i++){
f = getFunction(i);
f();
}
}
std::function<void()> Foo::getFunction(int i) {
switch(i){
case 0: return [this](){this->foo();};
case 1: return [this](){this->boo();};
case 2: return [this](){this->doo();};
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments