Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table of function pointers within a class C++

I'm trying to make a table of function pointers within a class. I haven't been able to find any examples of this online, most involve using member function pointers outside of their class.

for example:

class Test
{
    typedef void (Test::*FunctionType)();
    FunctionType table[0x100];

    void TestFunc()
    {
    }

    void FillTable()
    {
        for(int i = 0; i < 0x100; i++)
            table[i] = &Test::TestFunc;
    }   

    void Execute(int which)
    {
        table[which]();
    }
}test;

Gives me the error "term does not evaluate to a function taking 0 arguments".

like image 982
user741022 Avatar asked May 06 '11 03:05

user741022


People also ask

Can you have an array of function pointers in C?

In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.

What are function on pointers in C programming?

Function pointers in C can be used to create function calls to which they point. This allows programmers to pass them to functions as arguments. Such functions passed as an argument to other functions are also called callback functions.

What is a jump table in C?

A jump table is a special array of pointer-to-functions. Since, this is an array, and as we know that all array elements must be of same type, therefore, it requires that all functions must be of same type and all take same number and same type of parameters.

How do you define an array of function pointers?

Array of Function PointersWe declare and define four functions which take two integer arguments and return an integer value. These functions add, subtract, multiply and divide the two arguments regarding which function is being called by the user.


2 Answers

In this line in the Execute function:

table[which]();

You can't call it like that because it's not a normal function. You have to provide it with an object on which to operate, because it's a pointer to a member function, not a pointer to a function (there's a difference):

(this->*table[which])();

That will make the invoking object whichever object is pointed to by the this pointer (the one that's executing Execute).

Also, when posting errors, make sure to include the line on which the error occurs.

like image 125
Seth Carnegie Avatar answered Sep 20 '22 09:09

Seth Carnegie


Seth has the right answer. Next time, look up the compiler error number on MSDN and you'll see the same: Compiler Error C2064.

like image 37
sean e Avatar answered Sep 21 '22 09:09

sean e