无序映射:使用 class 成员函数指针的问题
Unordered map: issue using class member function pointer
我遇到以下问题:我正在编写一个简单的 chip8 模拟器,并且有大量 class 解释器函数,我想通过操作码作为键访问这些函数,例如使用字典。那是为了取代一个巨大的开关盒,我知道为此目的,无序地图是一个很好用的工具。
这种方法仅适用于函数(因为它们的静态作用域,我假设),但不适用于 classes,因为作用域的概念相同。我对指针和 C++ 本身有点陌生,我不确定如何解决这个问题(尝试了很多东西,例如使成员函数静态,指向函数的 class 实例等等 - 这些将不编译)。访问 iter->second returns 什么也没有,即使 map.count 说该成员存在。
#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
}
使用 header functional
中的 std::invoke
来执行它 (C++17):
test t;
std::invoke(iter->second, t);
毕竟,您需要在 object 上调用它。方法本身无法执行。
如果您没有 C++17 (IIRC):
test t;
(t.*(iter->second))();
我遇到以下问题:我正在编写一个简单的 chip8 模拟器,并且有大量 class 解释器函数,我想通过操作码作为键访问这些函数,例如使用字典。那是为了取代一个巨大的开关盒,我知道为此目的,无序地图是一个很好用的工具。
这种方法仅适用于函数(因为它们的静态作用域,我假设),但不适用于 classes,因为作用域的概念相同。我对指针和 C++ 本身有点陌生,我不确定如何解决这个问题(尝试了很多东西,例如使成员函数静态,指向函数的 class 实例等等 - 这些将不编译)。访问 iter->second returns 什么也没有,即使 map.count 说该成员存在。
#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
}
使用 header functional
中的 std::invoke
来执行它 (C++17):
test t;
std::invoke(iter->second, t);
毕竟,您需要在 object 上调用它。方法本身无法执行。
如果您没有 C++17 (IIRC):
test t;
(t.*(iter->second))();