Figuring out obscure pointer typedef
typedef solution_type (*algorithm_ptr_type) (
problem_type problem,
void (*post_evalua开发者_如何学JAVAtion_callback)(void *move, int score)/* = NULL*/
);
Please help me! Thank you
This means, algorithm_ptr_type is a pointer to a function returning solution_type and whose parameters are:
- problem of type
problem_type post_evaluation_callbackwhich is again a function pointer taking two parameters (void*andint) , and returningvoid.
And the same can be written as (easy and readable syntax):
typedef void (*callback_type)(void *move, int score);
typedef solution_type (*algorithm_type)(problem_type, callback_type);
Note: the name of the parameters are optional, so I removed it, to make the typedef short and cute!
In C++11, this can be simplified further as follows:
using algorithm_ptr_type = solution_type (*) (
problem_type,
void(*)(void*, int)
);
That is much better, as now it's clear as to what is being defined and in terms of what.
In C++11, you can even define a utility to create function-pointer as,
//first define a utility to make function pointer.
template<typename Return, typename ... Parameters>
using make_fn = Return (*)(Paramaters...);
then use it as,
using callback_type = make_fn<void, void*, int>;
using algorithm_type = make_fn<solution_type, problem_type, callback_type>;
Here the first argument to make_fn is the return type, and the rest are the parameters — easy to decipher each one!
Usage:
solution_type SomeFunction(problem_type problem, callback post_evaluation)
{
//implementation
//call the callback function
post_evaluation(arg1, arg2);
//..
}
algorithm_ptr_type function = SomeFunction;
//call the function
function(arg, someOtherFunction);
what a horrible piece of code!
what its doing is defining a function pointer type called algorithm_ptr_type, returning a solution_type and taking a problem_type as its first arg and a callback as its second arg. the callback takes void* and int as its args and returns nothing.
a better way to write this would be:
typedef void (*post_evaluation_callback)(void *move, int score);
typedef solution_type (*algorithm_ptr_type)(problem_type problem, post_evaluation_callback callback);
This frustrating piece of code makes it so that algorithm_ptr_type is a function pointer.
This type must point to a function that returns an object of type solution_type.
This type must point to a function that takes the following arguments:
0: An object of type problem_type.
1: A function pointer which must point to a function that:
Returns void.
Takes the following arguments:
0: A void*.
1: An int.
Defines solution_type as a function pointer to a function that takes a problem_type and another function pointer. This second function pointer takes a void* (anything) and an int as parameters.
加载中,请稍侯......
精彩评论