简体   繁体   English

是否可以将函数指针保留在std :: vector中?

[英]Is it possible to keep function pointers in an std::vector?

Is is possible to keep function pointers in an std::vector? 是否可以将函数指针保留在std :: vector中? And call each function in an iterator loop ? 并在迭代器循环中调用每个函数?

Ref : http://en.wikipedia.org/wiki/Function_pointer 参考: http : //en.wikipedia.org/wiki/Function_pointer

Is it possible to keep function pointers in an std::vector ? 是否可以将函数指针保留在std::vector

Sure, as long as they are all of the same type: 当然,只要它们都是同一类型:

void foo()
{
    std::cout << "inside foo\n";
}

void bar()
{
    std::cout << "inside bar\n";
}

void baz()
{
    std::cout << "inside baz\n";
}

std::vector<void(*)()> fps { foo, bar, baz };

And call each function in an iterator loop? 并在迭代器循环中调用每个函数?

No problem at all: 完全没有问题:

for (auto&& fp : fps)
{
    fp();
}

You might also want to consider the Boost Signals2 library. 您可能还需要考虑Boost Signals2库。 You can register any number of function pointers (AKA 'slots') to a 'signal' and have each one of them called by simply calling the 'signal' itself. 您可以将任何数量的函数指针(也称为“插槽”)注册到“信号”,并通过简单地调用“信号”本身来调用每个函数指针。 The library takes care of managing the list of function pointers and iterating through each of them as necessary. 该库负责管理函数指针列表,并在必要时遍历每个函数指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM