gpt4 book ai didi

c++ - C++:在子类中扩展静态STL容器/映射成员?

转载 作者:行者123 更新时间:2023-12-02 10:15:20 25 4
gpt4 key购买 nike

目前,我的代码看起来很像

#include <map>
#include <string>
#include <functional>

void SomeFunc();
void SomeOtherFunc();

struct Calls {
std::string name;
std::function<void(void)> a, b;
};

struct BaseClass
{
static const std::map<std::string, Calls> callbacks;
const std::map<std::string, Calls>* pCallbacks = &callbacks; // Run-time polymorphism, pointers are *typically* upcast back to base class.
};
const std::map<std::string, Calls> BaseClass::callbacks = {{"testX", {"x", SomeFunc, SomeOtherFunc}}};

void MoreFuncs();
void MoreFuncs2();

struct DerivedClass : BaseClass
{
static const std::map<std::string, Calls> callbacks;
const std::map<std::string, Calls>* pCallbacks = &callbacks;
};
const std::map<std::string, Calls> DerivedClass::callbacks = {
{"testX", {"x", SomeFunc, SomeOtherFunc}},
{"testY", {"g", MoreFuncs, MoreFuncs2}}};

struct DeepClass : DerivedClass
{
static const std::map<std::string, Calls> callbacks;
const std::map<std::string, Calls>* pCallbacks = &callbacks;
};
const std::map<std::string, Calls> DeepClass::callbacks = {
{"testX", {"x", SomeFunc, SomeOtherFunc}},
{"testY", {"g", MoreFuncs, MoreFuncs2}},
{"testZ", {"h", SomeOtherFunc, MoreFuncs2}},
};

更大的数量。
以这种方式进行扩展很累人,并且在我看来留下了太多的视觉集群。有什么技术可以使此操作更容易?

最佳答案

你可以写一个像

auto concat_maps(std::map<std::string, Calls> first, const std::map<std::string, Calls>& second)
{
first.insert(second.begin(), second.end());
return first;
}

将一张 map 合并到另一张 map 。这使您可以将派生类映射定义为父类映射和要添加的元素的串联。看起来像
struct DerivedClass : BaseClass
{
static const std::map<std::string, Calls> callbacks;
const std::map<std::string, Calls>* pCallbacks = &callbacks;
};
const std::map<std::string, Calls> DerivedClass::callbacks =
concat_maps( BaseClass::callbacks, {{"testY", {"g", MoreFuncs, MoreFuncs2}}});

struct DeepClass : DerivedClass
{
static const std::map<std::string, Calls> callbacks;
const std::map<std::string, Calls>* pCallbacks = &callbacks;
};
const std::map<std::string, Calls> DeepClass::callbacks =
concat_maps( DerivedClass::callbacks, {{"testZ", {"h", SomeOtherFunc, MoreFuncs2}}});

关于c++ - C++:在子类中扩展静态STL容器/映射成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62182762/

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