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

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

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

#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}},
};

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

c++ oop inheritance stl
1个回答
0
投票

您可以编写类似的函数

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

将一张地图合并到另一张地图中。这使您可以将派生类映射定义为父类映射和要添加的元素的串联。看起来像

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}}});
© www.soinside.com 2019 - 2024. All rights reserved.