1

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.

2
  • 1
    The first problem you have is that this code is written in C++, not C (as the question was originally tagged). The colons and the public keywords alone indicate that; the omnipresent & for references is also indicative. Commented Sep 12, 2013 at 2:01
  • I'm glad you're only asking about the typedefs; the bit that has me puzzled is the meaning of the GADefineIdentity("GAGenome", GAID::Genome); line. If it is a macro (perish the thought), then maybe it makes sense; but as code in a class definition ... I'm puzzled. Commented Sep 12, 2013 at 2:10

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.