是否可以选择创建包含不同返回类型的函数的向量?

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

我有以下向量

std::vector<std::pair<std::string, std::function<std::string(const PlayerFRDb&)>>> stringExtractors = {
    {" TEAM ", extractTeam},
    {" NAME ", extractName},
    {" TYPE ", extractProperty4},
};

std::vector<std::pair<std::string, std::function<int(const PlayerFRDb&)>>> intExtractors = {
    {" WS ", extractProperty0},
    {" LS ", extractProperty1},
    {" W ", extractProperty2},
    {" L ", extractProperty3},
};

std::vector<std::pair<std::string, std::function<char(const PlayerFRDb&)>>> charExtractors = {
    {" WAY ", extractProperty5},
};

std::vector<std::pair<std::string, std::function<double(const PlayerFRDb&)>>> doubleExtractors = {
    {" LINE ", extractProperty6},
};

为了更轻松地使用这些函数,我想将它们集中到一个向量中,但问题是它们返回不同的类型。

我尝试使用 std::variant,但无法初始化向量,因为编译器打印出:“没有构造函数的实例与参数列表参数类型匹配 ({...}, {...}, {...}、{...}、{...}、{...}、{...}、{...})

using FuncVariant = std::variant<
    std::function<std::string(const PlayerFRDb&)>,
    std::function<int(const PlayerFRDb&)>,
    std::function<double(const PlayerFRDb&)>
>;

std::vector<std::pair<std::string, FuncVariant>> extractors = {
    {" TEAM ", extractTeam},
    {" NAME ", extractName},
    {" TYPE ", extractProperty4},
    {" WS ", extractProperty0},
    {" LS ", extractProperty1},
    {" W ", extractProperty2},
    {" L ", extractProperty3},
    {" LINE ", extractProperty6},
};

是否可以选择创建包含不同返回类型的函数的向量?

c++ vector std-variant
1个回答
0
投票

您可以让函数类型返回一个变体,而不是让函数类型具有变体。

using FuncVariant = std::function<std::variant<std::string, int, double>(const PlayerFRDb&)>;

std::vector<std::pair<std::string, FuncVariant>> extractors = {
    {" TEAM ", extractTeam},
    {" NAME ", extractName},
    {" TYPE ", extractProperty4},
    {" WS ", extractProperty0},
    {" LS ", extractProperty1},
    {" W ", extractProperty2},
    {" L ", extractProperty3},
    {" LINE ", extractProperty6},
};
© www.soinside.com 2019 - 2024. All rights reserved.