C++:如何使用指向函数的指针的值创建成员 unordered_map
C++: How to create a member unordered_map with values of pointers to functions
This question 回答了常规 unordered_map
如何做到这一点,但是会员呢? IDE 报告注释中的错误。 opcodes
将字符映射到指向函数的指针,应该代表具体实例调用这些函数。另外我想知道是否有可能使它成为constexpr。
// Foo.cpp
class Foo {
public:
void execute(char c) { (*opcodes[c])(); }
void operation1()
{
// Do something with value_
}
void operation2();
private:
typedef void (*operation)();
static const std::unordered_map<char, operation> opcodes{
{'1', &Foo::operation1},
{'2', &Foo::operation2}
}; // No matching constructor for initialization of 'const std::unordered_map<char, operation>' (aka 'const unordered_map<char, void (*)()>')
int value_;
}
// main.cpp
int main()
{
Foo foo;
foo.execute('1');
return 0;
}
How to create a member unordered_map with values of pointers to functions?
像这样:
struct example {
using fun = return_type(/*arg types*/);
std::unordered_map<key_type, fun*> map;
};
typedef void (*operation)();
static const std::unordered_map<char, operation> opcodes{
{'1', &Foo::operation1},
{'2', &Foo::operation2}
}
问题在于您有一个指针函数映射,但您尝试使用指向成员函数的指针进行初始化。指向成员函数的指针不是指向函数的指针,不能转换为指向函数的指针。
因此,您需要的是指向成员函数的指针映射:
using operation = void (Foo::*)();
或者,您不需要使用非静态成员函数。
And how to call the [pointer to member] function after getting it from map?
示例:
(this->*opcodes.at('1'))();
This question 回答了常规 unordered_map
如何做到这一点,但是会员呢? IDE 报告注释中的错误。 opcodes
将字符映射到指向函数的指针,应该代表具体实例调用这些函数。另外我想知道是否有可能使它成为constexpr。
// Foo.cpp
class Foo {
public:
void execute(char c) { (*opcodes[c])(); }
void operation1()
{
// Do something with value_
}
void operation2();
private:
typedef void (*operation)();
static const std::unordered_map<char, operation> opcodes{
{'1', &Foo::operation1},
{'2', &Foo::operation2}
}; // No matching constructor for initialization of 'const std::unordered_map<char, operation>' (aka 'const unordered_map<char, void (*)()>')
int value_;
}
// main.cpp
int main()
{
Foo foo;
foo.execute('1');
return 0;
}
How to create a member unordered_map with values of pointers to functions?
像这样:
struct example {
using fun = return_type(/*arg types*/);
std::unordered_map<key_type, fun*> map;
};
typedef void (*operation)(); static const std::unordered_map<char, operation> opcodes{ {'1', &Foo::operation1}, {'2', &Foo::operation2} }
问题在于您有一个指针函数映射,但您尝试使用指向成员函数的指针进行初始化。指向成员函数的指针不是指向函数的指针,不能转换为指向函数的指针。
因此,您需要的是指向成员函数的指针映射:
using operation = void (Foo::*)();
或者,您不需要使用非静态成员函数。
And how to call the [pointer to member] function after getting it from map?
示例:
(this->*opcodes.at('1'))();