使用任何参数创建std :: functions的unordered_map?

问题描述 投票:2回答:3

我正在尝试创建一个无序的std::functions地图。键是一个字符串,您将在其中查找要调用的函数,函数是值。

我写了一个小程序:

#include <iostream>
#include <unordered_map>
#include <functional>
#include <string>

void func1()
{
  std::cout << "Function1 has been called." << std::endl;
}

int doMaths(int a)
{
  return a + 10;
}

int main()
{
  std::unordered_map<std::string,std::function<void()>> myMap;

  myMap["func1"] = func1;

}

编译得很好,我可以调用函数(但我不确定这是否是正确的方法):

auto mapIter = myMap.find("func1");
auto mapVal = mapIter->second;
mapVal();

然后调用该函数,但我认为这是以创建函数的新副本为代价的?如果我错了,请纠正我。

但是,如果我尝试这样做:myMap["doMaths"] = doMaths;我得到编译器错误,因为myMap中的值是std::function<void()>>而不是std::function<int(int)>>。当我做的时候,我确实得到了这个编译:myMap["doMaths"] = std::bind(doMaths,int());但是我不知道实际上是做什么的。当我尝试以与func1相同的方式调用它时,我得到编译器错误。

所以我想我有两个问题:

如何创建一个unordered_map,它将为它的值带来任何类型的函数?如何在不必复制函数的情况下调用地图中的函数?

c++ c++11 unordered-map
3个回答
4
投票

正如eerorika所说,你可以用std::any地图做到这一点。下面是一些示例代码,还显示了如何调用存储在地图中的函数指针:

#include <iostream>
#include <unordered_map>
#include <string>
#include <any>

void func1()
{
    std::cout << "Function1 has been called.\n";
}

int doMaths(int a)
{
    std::cout << "doMaths has been called, a = " << a << "\n";
    return a + 10;
}

int main()
{
    std::unordered_map<std::string,std::any> myMap;

    myMap["func1"] = func1;
    auto mapIter = myMap.find("func1");
    std::any_cast <void (*) ()> (mapIter->second) ();

    myMap["doMaths"] = doMaths;
    mapIter = myMap.find("doMaths");
    int result = std::any_cast <int (*) (int)> (mapIter->second) (5);
    std::cout << result;
}

Live demo

如果类型(或者,在这种情况下,函数签名)不匹配,std:any_cast将在运行时抛出std::bad_any_cast异常。

请注意:std::any需要C ++ 17,请参阅:https://en.cppreference.com/w/cpp/utility/any


1
投票

像保罗所说,但用std::function语法。您可以使用它来在地图中放置带有任何签名的函数,甚至是lambdas:D

#include <vector>
#include <iostream>
#include <functional>
#include <map>
#include <any>

int doMaths(int a)
{
    std::cout << "doMaths has been called, a = " << a << "\n";
    return a + 10;
}

int main()
{
  std::map<std::string, std::any> map;

  map["foo"] = std::function<int(int)>([](int a) { return a * 2; });

  map["bar"] = std::function<int(int, int)>([](int a, int b) { return a + b; });

  map["maths"] = std::function<int(int)>(doMaths);

  int a = std::any_cast<std::function<int(int)>>(map["foo"])(4);

  int b = std::any_cast<std::function<int(int, int)>>(map["bar"])(4, 5);

  int c = std::any_cast<std::function<int(int)>>(map["maths"])(5);

  std::cout << a << " " << b << " " << c <<std::endl;
}

在施法时要小心,你需要知道正确的签名和返回类型。


1
投票

如果您知道函数的类型是std::function<void(void)>,请将其放在std::unordered_map<std::string,std::function<void()>>中,并在那里查找。

如果您知道函数的类型是std::function<int(double, char)>,请将其放在std::unordered_map<std::string,std::function<int(double, char)>>中,并在那里查找。

如果您不知道函数的类型,则无法使用它,因此将它存储在地图中也没用。

如果您有多种类型的函数,也可以有多个映射。变量模板(或带有静态映射变量的函数模板)可以帮助创建任意数量的此类映射而无需复制任何代码。当然这种方式你只能拥有一张全球地图。可以管理这样一组地图的类可能会涉及更多,但只有一点。

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