我可以将异构函数散列到c ++中的unordered_map

问题描述 投票:0回答:1

我有一堆异构函数,我想使用std :: unordered_map来调用该函数,这样我们就不需要维护一个长的switch case列表。

这只是一个例子。

#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"]);

}

但即使存储它们(在void指针中),在调用时我们必须改变它的类型,有什么方法可以做得更好。

c++ unordered-map
1个回答
0
投票

但即使在存储它们之后(在void指针中),在调用时我们必须改变它的类型,有什么方法可以做得更好吗?

是的,对于异构函数类型,您可以使用std::variantstd::any来存储多个类型的单值,类似行为的联合。

https://en.cppreference.com/w/cpp/utility/variant

https://en.cppreference.com/w/cpp/utility/any

在您的示例中,它将被声明为:

std::variant<std::function<int()>, std::function<int(int)> >

特别是,使用std::variant,演员可以完全消失(但它可能感觉像一个开关)。

您可能还会发现使用std::function而不是原始函数指针更方便,更灵活,更安全。

https://en.cppreference.com/w/cpp/utility/functional/function

© www.soinside.com 2019 - 2024. All rights reserved.