C++ struct and typdef

c++

Solution

Concisely: `State` is an alias for function pointer.`State_` is a wrapper class that has a `State` member, and is implicitly convertible into that `State`.

The reason why `State_` wrapper is needed, is because there is no way to express a function that returns a pointer to a function of the same type. The wrapper gets rid of the self-reference.

Line by line:

struct StateData;

A forward declaration of a class `StateData`.

struct State_;

A forward declaration of a class `State_`.

typedef State_ (*State)(StateData&);

This one is a bit tricky. It defines `State` as a type alias for a function pointer that can point to a function that returns a `State_` and takes a `StateData&` as an argument. The functions declared at the end of the snippet can be pointed by a function pointer of this type.

In my opinion, the chosen name is very confusing considering that there is already a `State_` class. While I'm usually against hungarian notation, I would recommend to always apply a suffix or prefix to denote a function pointer, say `state_fun` or `state_handler` or `state_callback`,

struct State_
{

This starts the definition of `State_` calss.

    State_( State pp ) : p( pp ) { }

This defines a constructor for the class. The argument is of the function pointer type that was defined earlier. It initializes the member that will be declared shortly.

    operator State()
    {
        return p;
    }

A member function. More specifically, a user defined conversion into the function pointer type.

    State p;

Declares the member that was initialized in the constructor.

};

State_ state_start(StateData& d);
State_ state_selecting(StateData& d);
State_ state_initializing(StateData& d);
State_ state_tracking(StateData& d);

Free functions, that can be pointed by a `State`.

Problem

I am not sure about the title because I don't know what it is really about. I was trying to understand the code in the link below. Color Based Particle Filter I generally understand what the program does, but I couldn't figure out "state.h". What does this code do? Especially the "typedef", "State_" and "pp" parts look stranger to me. I will put some of the code here for clarity reasons. ``` struct StateData; struct State_; typedef State_ (*State)(StateData&); struct State_ { State_( State pp ) : p( pp ) { } operator State() { return p; } State p; }; State_ state_start(StateData& d); State_ state_selecting(StateData& d); State_ state_initializing(StateData& d); State_ state_tracking(StateData& d); ``` Any kind of help would be greatly appreciated.

Original source