从文本配置文件注册回调

时间:2010-12-14 21:12:40

标签: c++ maps

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

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

编辑:例如,我可能有:

void func1();
void func2();

void (*fptr[2])();

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

func1,0 func2,1

if-else表示我输入了一行,我得到一个字符串fname =“func1”和一个location_in_the_array,0。所以我会有一个块:

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

地图是一个好主意,它已经在我的大脑中掠过了几次,但我是一名太空军校学生,在我问之前忘了它。

3 个答案:

答案 0 :(得分:2)

假设文件格式如

  

一个
     ç
     一个
     B'/ P>

这应该解析它并相应地将函数指针放入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;
}

答案 1 :(得分:1)

  

如果你写下“使用地图”作为答案,我会选择它。

使用地图。

更具体地说,您的文本文件包含地图的键,地图将键映射到函数指针。为每个函数提供一个唯一的名称(可能是函数名称!如果你有重载,可能加上参数类型),将它存储在文本文件中,并通过映射运行每个条目以获取要存储的函数指针数组。

答案 2 :(得分:0)

间接会有帮助吗?

例如,获取函数指针,并在编译时按名称将它们分配给哈希表,也许是函数名称的标识符。

然后在运行时加载文本文件,这是一个名称列表。

通过查找标识符创建一个数组,在哈希表中找到它的函数指针,然后填充数组。