简体   繁体   中英

Static member array of pointers to member functions


I am trying to define in a .cpp file an attribute which should be an array of pointers to member functions of a class named Hand.
Both the array and the functions are members of Hand and the array is static(please correct me if it should not).
This is what I reached:

static bool Hand::*(Hand::hfunctions)[] ()=
{&Hand::has_sflush,&Hand::has_poker,&Hand::has_full,&Hand::has_flush,
&Hand::has_straight,&Hand::has_trio,&Hand::has_2pair,&Hand::has_pair};                                              


I get this error: hand.cpp:96:42: error: declaration of 'hfunctions' as array of functions.
I guess the type definition is worng so I need to know how can I make the definition right

The syntax is a rather convoluted one:

class Hand
{
    bool has_sflush();
    static bool (Hand::*hfunctions[])();
    ...
};

bool (Hand::*Hand::hfunctions[])() = {&Hand::has_sflush, ...};

A way to get to this is by gradually increasing complexity, using cdecl.org to check yourself at each step:

int (*hFunctions)()

declare hFunctions as pointer to function returning int


int (Hand::*hFunctions)()

declare hFunctions as pointer to member of class Hand function returning int

Warning: Unsupported in C -- 'pointer to member of class'


int (Hand::*hFunctions[])()

declare hFunctions as array of pointer to member of class Hand function returning int

Warning: Unsupported in C -- 'pointer to member of class'


Now replace int by bool (sadly, cdecl.org doesn't understand bool ); so you get the syntax of the declaration.

For the definition, replace hFunctions by Hand::hFunctions, and add the initialization part, like you did.

Both the array and the functions are members of Hand and the array is static(please correct me if it should not).

If I understand correctly what you are asking, you should not . You should abstract the operation as a base class, specialize it and hold the array as an array of pointers to the base class:

struct Match // need a better name
{
     virtual bool matches() = 0;
     virtual ~Match() = default;
};

struct MatchSFlush: public Match { ... };

class Hand
{
    static std::vector<std::unique_ptr<Match>> matches;
};

If you have non static member functions with no arguments and returning bool you should write something like

typedef bool (Hand::*hfunction_non_static)();
hfunction_non_static f_non_static [] =
{
    &Hand::has_sflush,
    &Hand::has_poker,
    .......
}; 
Hand h;
(h.*f_non_static[0])();

If you have static functions you should write something like

typedef bool (*hfunction_static)();
hfunction_static f_static [] = {&Hand::has_sflush, ....};
f_static[0]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM