初始化多态函数指针映射

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

我正在做一个个人项目,它可以归结为一个任务管理命令行工具。这个想法是采用我在高级语言中使用的一些概念并将它们应用到 C++ 中,并习惯 SQLite C/C++ API。但我离题了

实现的想法是使用静态 SchemaBuilder.build() 方法,该方法接受字符串向量并相应地解析它。由于我们不能在 C++ 中使用带有字符串文字的 switch 语句,因此我默认使用之前用于命令解析器的策略,即使用 std::map

我在编译它时遇到了一些困难。这是代码:

#include <vector>
#include <map>

class TableSchema{
};

class TaskSchema : public TableSchema{
};

class ProjectSchema : public TableSchema{
};

typedef TableSchema* (*BuildFunction)(std::vector<std::string> args);

class SchemaBuilder{
public:
    static TableSchema* build(std::vector<std::string> args); 
};

TaskSchema* buildTask(std::vector<std::string>);
ProjectSchema* buildProject(std::vector<std::string>);

std::map<std::string, BuildFunction> buildMap = {
    { "task", buildTask },
    { "project", buildProject }
};

//weirdest part is that this one compiles while the above one doesn't
void tmp(){
    std::map<std::string, BuildFunction> tmp;
    tmp["task"] = buildTask;
    tmp["project"] = buildProject;
}

TaskSchema* buildTask(std::vector<std::string> params){
    return nullptr; 
}

ProjectSchema* buildProject(std::vector<std::string> params){
    return new ProjectSchema(params[0], params[1]);
}

错误信息:

src/schema-builder.cpp:6:1: error: could not convert ‘{{"task", buildTask}, {"project", buildProject}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::__cxx11::basic_string<char>, TableSchema* (*)(std::vector<std::__cxx11::basic_string<char> >)>’
    6 | };
      | ^
      | |
      | <brace-enclosed initializer list>

tmp 函数不是项目的一部分,只是一个测试,看看我正在做的事情是否可编译 - 它是

不用说,ProjectSchema 和 TaskSchema 都公开继承自 TableSchema

任何帮助将不胜感激

c++ function dictionary pointers polymorphism
1个回答
0
投票

开始工作了

#include <vector>
#include <map>

class TableSchema{
  //polymorphic behaviour through virtual methods
};

class TaskSchema : public TableSchema{
  //polymorphic behaviour through [type] [method_name]([params][]) override
};

class ProjectSchema : public TableSchema{
};

typedef std::unique_ptr<TableSchema> (*BuildFunction)(std::vector<std::string> args);

class SchemaBuilder{
public:
    static TableSchema* build(std::vector<std::string> args); 
};

std::unique_ptr<TableSchema> buildTask(std::vector<std::string>);
std::unique_ptr<TableSchema> buildProject(std::vector<std::string>);

std::map<std::string, BuildFunction> buildMap = {
    { "task", buildTask },
    { "project", buildProject }
};

std::unique_ptr<TableSchema> buildTask(std::vector<std::string> params){
    return nullptr; 
}

std::unique_ptr<TableSchema> buildProject(std::vector<std::string> params){
    return new ProjectSchema(params[0], params[1]);
}

无论你是谁,下次你提出问题并最终解决自己的问题时,请记住这一点。有时回答自己就是帮助世界

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