In javascript it’s possible to do things like this:
SomeObject.somefunction(function(someparameters){
//do some things.
});
like in jquery each function:
$('.rawdata').each(function(index){
$(this).attr('some',index);
});
I searched and saw that in c/c++ we can use functions as parameters using function pointers, but didn’t found a way to do some thing like the above one: to declare the function that will be pointed in the moment that it will be used. So is this possible? If it isn’t, what would you recommend to use instead?
Check out lambda functions, added to C++ in the latest standard (C++11).
The parameter that will receive the function will have to be either a template (whose precise type will be automatically deducted from the lambda function itself), either
std::function<>(a type-erasure class designed to hold any type of “callable thing” with the given prototype).By the way, function pointers aren’t the only way to pass a function-like object to a procedure in C++ even before the C++11 standard: any object that overloads
operator()(i.e. the function call operator) can be called as a function, and is said to be a “functor”. Functors are quite ubiquitous when programming with the STL1 algorithms.