Angus Comber
Angus Comber

Reputation: 9708

How to call this function pointer

I am getting a C2064 error below below in trying to invoke a function. What am I doing wrong?

//error C2064: term does not evaluate to a function taking 1 arguments
#include <iostream>
#include <string>

using namespace std;

class DXStartupEncoder {
public:
   void EncodeA(string& message) const { message = "A"; }
   void EncodeB(string& message) const { message = "B"; }
   void EncodeC(string& message) const { message = "C"; }
   void EncodeD(string& message) const { message = "D"; }
   void EncodeE(string& message) const { message = "E"; }
   void EncodeF(string& message) const { message = "F"; }
};

typedef void (DXStartupEncoder::*Encoder)(string&) const;
Encoder dn_sequence[] = {&DXStartupEncoder::EncodeA, &DXStartupEncoder::EncodeB, &DXStartupEncoder::EncodeC, &DXStartupEncoder::EncodeD };
Encoder queue_sequence[] = { &DXStartupEncoder::EncodeE, &DXStartupEncoder::EncodeF };


int main(int argc, char* argv[])
{
   for(int i = 0; i < sizeof(queue_sequence) / sizeof(queue_sequence[0]); ++i) {
      string param;
      queue_sequence[i](param);  //How to call function here???
      cout << param << endl;
   }

   return 0;
}

Upvotes: 0

Views: 155

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283644

You don't have function pointers, you have an array of pointer-to-member-function. You have to supply the this object when dereferencing a pointer-to-member.

(obj.*queue_sequence[i])(param);  //obj must have type DXStartupEncoder

Alternatively, since your functions are stateless, you can make them static and then use ordinary function pointers.

typedef void (*Encoder)(string&) const;

Upvotes: 4

Related Questions