带字符串的无序映射和接收字符串的函数。

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

我用的是C++11,不能用C++17。

我把我的unordered_map声明为。

std::unordered_map<std::string, std::function<int(char*)>> htFunctions;

我的函数 都是这样的。

int inFunction01(char *data);
int inFunction02(char *data);
...
int inFunction14(char *data);

我有15个左右的函数,做着不同的事情 但它们都有相同的声明。也就是说,它们返回一个int并接收一个char数组。

我插入的元素是这样的。

htFunctions.insert({"FN1", inFunction01});

但是当我试图通过 operator[]来捕捉函数调用的结果时,

inRet = htFunctions["FN1"];

我在编译时得到了以下的错误。

../src/main.cpp:259:31: error: cannot convert 'std::__detail::_Map_base<std::basic_string<char>,std::pair<const std::basic_string<char>, std::function<int(char*)> >, std::_Select1st<std::pair<const std::basic_string<char>,std::function<int(char*)> > >, true, std::_Hashtable<std::basic_string<char>,std::pair<const std::basic_string<char>, std::function<int(char*)> >, std::allocator<std::pair<const std::basic_string<char>, std::function<int(char*)> > >, std::_Select1st<std::pair<const std::basic_string<char>, std::function<int(char*)> > >, std::equal_to<std::basic_string<char> >, std::hash<std::basic_string<char> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, true, false, true> >::mapped_type {aka std::function<int(char*)>}' to 'int' in assignment

并且在Visual Code上得到以下警告错误:

没有合适的从 "std::function "到 "int "的转换函数存在。

据我了解,当我做 std::unordered_map<std::string, std::function<int(char*)>> htFunctions;,什么部分 std::function<int(char*)> 意思是 "返回一个int的函数,参数类型为 char*'

但我想这样做是不对的,我应该用什么正确的方式来实现。std::function<>我的功能?

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

你仍然需要向你的函数传递参数。

假设,你的一个函数做了以下的事情。

int inFunction01(char *data){
    return 42;
}

然后你把它插入到你的哈希表中。

htFunctions.insert({ "FN1", inFunction01 });

捕捉函数的结果 inFunction01 将需要把 "FN1 "的值作为一个接受参数的函数来处理,例如。

int inRet = htFunctions["FN1"]("Get my 42 answer please");
cout << inRet << '\n';

将输出 42.

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