У меня есть куча разнородных функций, я хочу использовать std :: unordered_map для вызова этой функции, чтобы нам не нужно было поддерживать длинный список вариантов переключения.
Это всего лишь пример.
#include <iostream>
#include <unordered_map>
using namespace std;
void hello()
{
cout << "hello"<<endl;
}
int hello1()
{
cout << "hello1"<<endl;
return 1;
}
int hello2(int x)
{
cout << "hello2" << endl;
cout << x;
return x;
}
int main()
{
unordered_map<string, void*> map;
map["hello"] = (void*)hello;
map["hello1"] = (void*)hello1;
map["hello2"] = (void*)hello2;
if(map.find("hello2") != map.end())
{
func = map["hello2"].second;
}
cout << reinterpret_cast<int(*)(int)>(map["hello2"])(2);
cout <<endl;
cout << reinterpret_cast<int(*)()>(map["hello1"]);
}
Но даже после их сохранения (в пустом указателе) во время вызова мы должны изменить его тип, есть ли способ сделать это лучше.