1

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 );
1

2 Answers 2

5

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 ->*.

Sign up to request clarification or add additional context in comments.

2 Comments

WOW! FAST answer! & Absolutely correct too! Thank you so much. Thank you for the explanation too... I was screwing up the member access operator having higher precedence than the function operator.
@Eric: Fast? Nah, that was 8 minutes after you asked. :) I was stumped that noone answered yet. ;)
2

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

1 Comment

Thank you! Your post helped my understanding too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.