无序映射:使用类成员函数指针的问题 [英] Unordered map: issue using class member function pointer

查看:94
本文介绍了无序映射:使用类成员函数指针的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题:我正在编写一个简单的chip8仿真器,并且具有大量的解释器函数类,我想通过操作码作为键来访问它们,例如字典.那是要替换庞大的开关盒,我知道为此目的,无序映射是一个很好的使用工具.

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.

由于作用域的概念相同,因此这种方法仅适用于函数(由于它们的静态作用域),因此很容易使用,而不适用于类.我对指针和C ++本身有些陌生,并且不确定如何解决该问题(尝试了很多工作,例如使成员函数静态化,指向该函数的类实例等-这些将无法编译).即使it .-> second访问也不返回任何内容,即使map.count表示该成员存在.

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
}

推荐答案

使用标题functional中的std::invoke来执行它(C ++ 17):

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.

如果您没有C ++ 17(IIRC):

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

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

这篇关于无序映射:使用类成员函数指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆