Unordered map: issue using class member function pointer

丶灬走出姿态 提交于 2019-12-19 11:58:08

问题


I have the following problem: I am writing a simple chip8 emulator, and have a massive class of interpreter functions that I would like to access via opcodes as keys, such as with a dictionary. That is to replace a massive switch case, and I understand that for that purpose, an unordered map is a nice tool to use.

This approach works easily with just functions (because of their static scope, I assume), but does not with classes, because of the same concept of scope. I am somewhat new to pointers and C++ itself, and am not sure how to resolve the issue (having tried a lot of stuff, e.g making member functions static, pointing to a class instance of the function and such - these will not compile). Accessing iter->second returns nothing at all, even though map.count says that the member exists.

#include <cstdio>
#include <unordered_map>

class test{
public:
    test();
    void fptr(void);
};

void test::fptr(void){
    printf("fptr\n");
}

typedef void (test::*Interpreter)(void);
typedef std::unordered_map<int, Interpreter> fmap;

int main(void){
    fmap map;
    int input = 0;

    map.emplace(1, &test::fptr);

    printf("input int to access:\n");
    scanf("%i", &input);

    auto iter = map.find(input);
    if(iter == map.end() ){
        printf("No such function\n");
    }
    else{
        iter->second; //iter->second() will not compile, accessing like this returns nothing
    }

//checks that the emplaced function actually exists
    for (auto& x: {1}) {
    if (map.count(x)>0){ 
        printf("map has %i\n", x);
    }
    else {
        printf("map has no %i\n", x);
    }

    return 0
}

回答1:


Use std::invoke from the header functional to execute it (C++17):

test t;
std::invoke(iter->second, t);

After all, you need to invoke it on an object. The method on its own cannot be executed.

If you don't have C++17 (IIRC):

test t;
(t.*(iter->second))();


来源:https://stackoverflow.com/questions/53748542/unordered-map-issue-using-class-member-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!