c++ - 特殊结构 : grouping of (pointers to function and groupings of pointers to function)

标签 c++ struct unions

我需要声明一个包含函数指针列表的“东西”,我需要以两种方式访问​​它们:

  • 直接调用function.myStructVar.attr1

  • vector.myStructVar.vec[1]

  • 一样循环遍历它们

因此,我想:“struct + union 是我的解决方案”我将声明一个包含我想要的变量的结构,然后声明一个包含该结构的 union 和一个函数指针 vector 。

但是事情变得更加复杂了。现在,我不想只使用指向函数的指针,而是想将指向函数的指针与指向函数的指针容器混合在一起。 (我知道,这很奇怪,我不是很清楚 :S)

恢复:我想要一组(指向函数的指针和指向函数的指针的分组)。我希望能够以一种我不需要知道它们的结构的方式访问它们。

这可能吗?怎么办?

最终目标: 我想要这样的对象:

对象A:

-Eat Apple
-Eat Bannana
--DoDigestion(this is a:
-->DigestApple
-->DigestBannana
-->AddAcid
)

对象B:

-Eat Potato
-Eat Bannana
--DoDigestion(this is a:
-->DigestBannana
-->AddWater
)

最后,我们的想法是定义某种将要完成的规范,并将其发送给将要执行的函数:

执行者:

    void execute(Object):
       foreach(Action a in Object) do(a);
       foreach(GroupOfAction g in Object) execute(g);

最佳答案

简单的解决方案是将您的 GroupOfAction进入Action本身。然后给你正在寻找的“东西” GroupOfAction ,现在可以包含子组。

C++11 已经有一个“Action”类,std::function<void(void)> .所以:

typedef std::function<void(void)> Action;
typedef std::list<Action> GroupOfAction;
Action Group(GroupOfAction const& list)
{
  return [list](){ for (Action& a : list) { a(); } }
}

关于c++ - 特殊结构 : grouping of (pointers to function and groupings of pointers to function),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13049911/

相关文章:

c++ - union 和位字段交互如何工作?

float 和字节数组问题的 C++ union

c++ - std::function 检查类的继承

c++ - 遍历链表的列表

在两个结构体数组变量之间复制数据

c - 尝试使用调用 stat 的 ctime 返回值对 c 中的结构数组进行排序

c++ - 为什么要将结构包装在匿名 union 中? (STL msvc 实现)

c++ - 捕获 C++ 中构造函数抛出的错误?

c++ - 是否可以在 C++ 中实现事件?

c++ - 如何在 MFC 中重定向 TRACE 语句以减少来自 AfxDumpStack() 的数据流?