So my first question is why is the author using a direct ad here?
So, the compiler knows that GameCharacter is a valid name when the string int defaultHealthCalc(const GameCharacter& gc); .
And my second question: how to understand typedef declaration and how to use it?
Ideally, you no longer use it.
Starting with C ++ 11, using is an excellent alternative because it is more readable; unlike typedef 'ed function pointers, it clearly separates the name from the name that describes the name. Compare this:
typedef int (*HealthCalcFunc)(const GameCharacter&);
Wherein:
using HealthCalcFunc = int (*)(const GameCharacter&);
In the typedef version, the name HealthCalcFunc is surrounded on both sides by what the name describes. This affects readability.
But the code can still be improved, because C ++ 11 also introduced std::function as an alternative and / or level of abstraction over function pointers.
using HealthCalcFunc = std::function<int(const GameCharacter&)>;
It is so readable that it hardly needs to be explained at all. HealthCalcFunc is a function that returns int and accepts const GameCharacter& .
The defaultHealthCalc function fits into this definition. Here is a complete example:
#include <functional> class GameCharacter; int defaultHealthCalc(const GameCharacter& gc); class GameCharacter { public: using HealthCalcFunc = std::function<int(const GameCharacter&)>; explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) : healthFunc(hcf) {} int healthValue() const {return healthFunc(*this); } private: HealthCalcFunc healthFunc; };
The great thing about std::function is that you are not limited to stand-alone functions. You can pass each function. Here are some examples:
struct Functor { int f(const GameCharacter& gc); }; int main() {
See also Should I use std :: function or function pointer in C ++? .