0

I'm new to function pointers and am getting hung up on syntax. What I'm trying to do is define, within a class, an array of functions to do string matching. The matching functions and their storing array will be static since they will be shared by all instances of the class. The functions are stored in an array so I can iterate through within match() and try different ones. Also, I'm trying to typedef the function pointer globally because similar matching functions will be used in many such classes. I've found some stuff suggesting that the signature should maybe be bool(Money::FP)(char str) but, if true, is there no way that I can define this globally (i.e. for classes other than "Money")?

The code below does not compile so please consider it as pseudocode for what I'm trying to accomplish.

Money.h:

typedef bool(*FP)(char* str);

class Money
{

private:
    static FP matchers[3] = {
        Money::m1,
        Money::m2,
        Money::m3
    };

    static bool m1(char* str);
    static bool m2(char* str);
    static bool m3(char* str);

public:
    static void match(char* str);
};
Gadzooks34
  • 1,718
  • 2
  • 20
  • 29

1 Answers1

2

It's not working because Money::m1 refers to Money type inside its declaration. Try to decouple them, eg

class Money {
  private:
    static FP matchers[3];
};

FP Money::matchers[3] = {
        Money::m1,
        Money::m2,
        Money::m3
    };

In any case you might consider using std::function<bool(char*)> instead that a function pointer, since you are working with C++. Performance is not an issue until you prove it to be an issue.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • OK. Trying to get this approach to work but I'm running into linker issues: unresolved external symbol "public: static bool __cdecl Money::m1(char *)" (?m1@Money@@SA_NPAD@Z). Is this related to the function pointer signature being wrong? I didn't know about the std::function object. I'll look into it. – Gadzooks34 Jan 08 '16 at 19:26
  • `std::function` is *not* a replacement for function pointers. It is a heavyweight functionoid type eraser. – Quentin Jan 08 '16 at 19:34
  • @Quentin: std::function can wrap any kind of callable pbject, including a function pointer but not limiting to it. They provide useful higher order behavior so I don't see the point. Functions pointers are valid and the only choice when interfacing with legacy code but std::function is a valid alternative. – Jack Jan 09 '16 at 16:53
  • @Jack When the additional functionality is completely superfluous, as it is here, then the tool is simply not fit for the job. Premature optimisation is one thing, pulling out the most complex and heavy tool of your box just for the sake of using it is premature pessimization. Which, admittedly, is hidden behind `std::function`'s friendly interface. Function pointers are not closer to legacy than any other pointer types are, now that we've got standard smart pointers and functionoid wrappers. – Quentin Jan 09 '16 at 17:19