我需要声明一个包含函数指针列表的“东西”,我需要以两种方式访问它们:
直接调用
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/