简体   繁体   中英

C++ Function Pointer

Is this possible? If so, I can't seem to get the syntax right. (C++ function pointer)

bit of background. The code below has been shorten for this post. The reason for this implementation is to avoid an endless list of SWITCH/CASE or IF/ELSEIF statements; and have an endless list of DECODER_FUNCTION_TABLE (see below). This code deals with an industry standard that uses mnemonics to mean different things and there are hundreds of these mnemonics. So this portion of my code is to decode certain mnemonics pass to it from another section of code that loops through a passed in record... anyway my difficulty is in keeping a member function pointer in a structure outside of the class...

Have a look. I think the code may do a better job explaining ;)

typedef struct _DECODER_FUNCTION_RECS
{
  ISO_MNEMONIC_ID Mnemonic;
  void (Database::*pFn)(Database::Rec *);

}DECODER_FUNCTION_RECS;


DECODER_FUNCTION_RECS DECODER_FUNCTION_TABLE[] = {

  SFP, &Database::Decode_SFP,
  KOG, &Database::Decode_KOG
};


void Database::DecodedDescription(Rec *A)
{

  int i = 0;
  bool Found = false;

  while( i < DECODER_FUNCTION_TABLE_COUNT && !Found )
  {
    if( DECODER_FUNCTION_TABLE[i].Mnemonic == A->Mnemonic )
      Found = true;
    else
      i++;
  }

  if( Found )
    (([DECODER_FUNCTION_TABLE[i]).*this.*pFn)( A );

}


void Database::Decode_SFP(Rec *A)
{
  // do decode stuff on A
}

The detail I'm trying to work out is this line:

 (([DECODER_FUNCTION_TABLE[i]).*this.*pFn)( A );

You call a member function pointer (that's what it's called) with

(this->*DECODER_FUNCTION_TABLE[i].pFn)(A);

Could put parens around DECODER_FUNCTION_TABLE[i].pFn , but the member access operator . has a higher precedence than member function operator ->* .

I wrote up a few simple examples that will shed some light the other day

It's in my answer to this question

error C2664 and C2597 in OpenGL and DevIL in C++

Or a direct link to codepad

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