I have a simple code as below:
int global1(int x)
{
return x * 5;
}
int global2(int x)
{
return x + 5;
}
struct some_struct {
int a;
int foo1(int x)
{
return x * a;
}
int foo2(int x)
{
return x + a;
}
int bar1(int x, bool a)
{
auto func = a ? global1 : global2; // works
// auto func = a ? &global1 : &global2; // also works
return func(x);
}
int problem_function(int x, bool a) // It is my question
{
auto func = a ? foo1 : foo2; // gives error
// auto func = a ? &foo1 : &foo2; // also gives error
// auto func = a ? &this->foo1 : &this->foo2; // also gives error
return func(x);
}
};
It is a very simplified form of the real code. I have no way to carry function on the outside like how I did in this with global1() & global2().
I want to call one of the functions in the struct, but using a pointer to a function, but it gives an error.
Note: I can't use if..else because in the real code it doesn't return func(x). In the real code, I use func(x) as a condition for a function in a loop (I am not joking, it's literaly what I said).
A part from the real code:
void* find_first(ExprToken* (*cond)(bool (*)(ExprToken*))) {...} // yeah
I know if I want to call a function of a struct, I have to tell the compiler which variable (struct) I am using, but how?
Does C++ even support a function pointer in a struct?
Sorry for the complexity, sometimes I forget what the real code is actually doing.
c++ call pointer to member function.std::functiontogether withstd::bindor lambdas; Or use templates (again withstd::bindor lambdas), which is how the C++ standard library handles all its callable objects.,if..elsebecause in the real code it doesn't returnfunc(x)." -- I don't buy this. Mostly because you could write a function that returnsfunc(x)and use that new function in place of the loop conditional. Break your messy functions into smaller pieces, and perceived problems like this tend to vanish. A few type aliases could also help.