Reputation: 7458
I came across some code with various typedefs as follows:
class GAGenome : public GAID {
public: GADefineIdentity("GAGenome", GAID::Genome);
public:
typedef float (*Evaluator)(GAGenome &);
typedef void (*Initializer)(GAGenome &);
typedef int (*Mutator)(GAGenome &, float);
typedef float (*Comparator)(const GAGenome&, const GAGenome&);
typedef int (*SexualCrossover)(const GAGenome&, const GAGenome&,
GAGenome*, GAGenome*);
typedef int (*AsexualCrossover)(const GAGenome&, GAGenome*);
//some other code
I don't understand the 'typedef' usage here, so can anyone teach me what does it mean? It looks a little bit complex here.
Upvotes: 1
Views: 117
Reputation: 37202
Those lines are defining types that can be used as pointers to functions.
typedef float (*Evaluator)(GAGenome &);
This defines the Evaluator
type as a pointer to a function that takes a reference to GAGenome
as its single parameter, and returns a float
.
You could use it like this:
float my_Evaluator_Function(GAGenome& g)
{
// code
return val;
}
GAGenome::Evaluator pfnEval = my_Evaluator_Function;
float val = pfnEval(myGenome);
Upvotes: 2
Reputation: 755064
All six typedef
declarations specify pointers to functions of various sorts.
The first says that a variable of type GAGenome::Evaluator
is a pointer to a function that takes a (non-constant) GAGenome
reference and returns a float
value. That is, given:
GAGenome x = ...suitable initializer...;
GAGenome::Evaluator e = ...suitable function name...;
float f = e(x); // Call the function whose pointer is stored in e
The other function pointer types are similar, each with their own slightly different meaning due to the different return type or sets of parameters.
Upvotes: 1