gpt4 book ai didi

c++ - 从文本配置文件注册回调

转载 作者:行者123 更新时间:2023-11-28 01:09:05 25 4
gpt4 key购买 nike

我有一个普遍的问题,我有一个函数指针数组。挑战在于根据文本配置文件将函数绑定(bind)到数组中的位置。有没有比巨大的 if-else-else-...-else block 更好的方法来做到这一点?

是否更容易实现仿函数并将位置绑定(bind)到类型的实例?

编辑:例如,我可能有:

void func1();
void func2();

void (*fptr[2])();

我想要一个输入配置文件,告诉我 func1 进入 fptr[0],func2 进入 fptr[1]。

函数 1, 0函数 2, 1

if-else 意味着我流式传输行,我得到一个字符串 fname = "func1",和一个 location_in_the_array, 0。所以我将有一个 block :

if (fname.compare("func1")) 
{
fptr[location_in_the_array] = func1;
}
else if (...) {}

一张 map 是个好主意,它在我的脑海中闪过几次,但我是一名太空学员,在我问之前就忘记了。

最佳答案

假设文件格式如

a
c
a
b

这应该解析它并相应地将函数指针放入 std::vector 中:

// Beware, untested code ahead!

typedef void (*func_t)();
typedef std::map<std::string, func_t> func_map_t;
typedef func_map_t::value_type func_map_entry_t;

void f1() {}
void f2() {}
void f3() {}

const func_map_entry_t func_map_entries[] = { func_map_entry_t("a", &f1)
, func_map_entry_t("b", &f2)
, func_map_entry_t("c", &f3) };

const func_map_t func_map( func_map_entries
, func_map_entries + sizeof(func_map_entries)
/ sizeof(func_map_entries[0]));

func_t read_line(std::istream& is)
{
std::string token;
if(!(is >> token)) throw "you need better error handling!";
func_map_t::const_iterator found = func_map.find(token);
if(found == func_map.end()) throw "you need better error handling!";
return found->second;
}

std::vector<func_t> read_config(std::istream& is)
{
std::vector<func_t> result;
std::string line;
while(std::getline(is,line))
{
std::istringstream iss(line);
func_t func = read_line(iss);
if(!func) throw "you need better error handling!";
result.push_back(func);
}
if(is.eof()) throw "you need better error handling!";
return result;
}

关于c++ - 从文本配置文件注册回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4444293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com