Zizhao
Zizhao

Reputation: 259

How to call function pointer in STL

I am curious about how to call function pointer in a map structure. Here is the details:

#include<iostream>
#include<map>
#include<vector>
#include<string.h>

using namespace std;
class FuncP;

typedef int(FuncP::*func) (int, int);
class FuncP
{
public:
    map<int, func> fmap;
    map<int, string> fstring;
public:
    FuncP(){}
    void initial();
    int max(int x, int y);
    int min(int x, int y);
    int call(int op, int x, int y)
    {
        return (this->*fmap[op])(x, y);
    }
};


void FuncP::initial()
{
    fmap[0] = &FuncP::max;
    fmap[1] = &FuncP::min;
    fstring[0] = "fdsfaf";
}
int FuncP::min(int x, int y)
{
    return (x<y)?x:y;
}
int FuncP::max(int x, int y)
{
    return (x<y)?y:x;   
}

int main()
{
    func h = &FuncP::max;
    FuncP *handle = new FuncP();
    handle->initial();

    cout<< handle->call(0, 1, 4);  //1
    cout<< (handle->FuncP::*fmap)[0](1,5);  //2
    return 0;
}

For the number 2 (handle->FuncP::*fmap)0; The compiler gives a error:

‘fmap’ was not declared in this scope

I am not sure why it happened. What the difference of the number 1 and 2 call methods?

Upvotes: 0

Views: 378

Answers (1)

wonce
wonce

Reputation: 1921

As commented by Piotr, a correct way would be

(handle->*(handle->fmap[0]))(1, 5);

Explanation: handle->fmap[0] gives you the function pointer. To call it, you need to dereference it, giving *(handle->fmap[0]) (parentheses optional) and call it on the respecting object (handle), leaving us with the expression above.

This is essentially the same as your above statement (this->*fmap[op])(x, y) except of handle->fmap[0]instead offmap[op].

Upvotes: 2

Related Questions