OP found a solution using function pointers. He chose to pass the pointer through the constructor and store it in the class. Another possibility is to pass the function pointer directly to the function execute
:
class T {
public:
double execute(double (*expression)()) {
return expression();
}
};
int main() {
T t;
double result = t.execute([]() -> double {return 1 + 1;});
return 0;
}
Function pointers have a strange syntax, do not allow capturing context variables (i.e, closures) and inlining.
In case you need closures or inline it is possible to use a template to generalize the expression. For most cases this is the best way to pass any function as a parameter:
class T {
public:
template<typename Func>
double execute(Func expression) {
return expression();
}
};
int main() {
T t;
int a = 0, b = 1;
double result = t.execute([&a,&b]() -> double {return 3 * a + 5 * b;});
return 0;
}
The main limitations of the version with template sane:
- Cannot "store" this type outside the class
- The implementation needs to be close to the header
If the above limitations are a problem, it is possible to resort to std::function
, one wrapper for function pointers, functors, Amble, etc..
class T {
public:
double execute(std::function<double()> expression) {
// sem templates, expression pode ser "armazenada" em qualquer lugar
return expression();
}
};
int main() {
T t;
int a = 0, b = 1;
// [&] captura qualquer variavel por referencia
std::function<double()> func = [&]() -> double {return 3 * a + 5 * b;};
double result = t.execute(func);
return 0;
}
While using std::function
is more generic when compared to function pointers, the wrapper results in overhead during the call. It is also not possible to use std::function
with versions prior to C++11 or with inline
.
References:
- Soen: Should I use Std::Function or a Function Pointer in C++?
- Lambda Functions in C++11 - the Definitive Guide
Very good this solution with the rapper. The advantage of being able to be stored stands out over the disadvantage of overhead. In addition the syntax is much clearer.
– Michael Pacheco
Yes, to be fair you could "store" a reference using the template within the class itself (the biggest flaw in my opinion of this approach, in my opinion, is that function templates do not work right with
auto
). That said, from the point of view of designstd::function
is really quite flexible.– Anthony Accioly