开发者

Calling all functors in a container

开发者 https://www.devze.com 2023-01-31 10:04 出处:网络
I have a sequence of std::function objects (a very primitive form of signal system). Is there a standard (in C++0x) function or functor that will call given std::function?For now I use

I have a sequence of std::function objects (a very primitive form of signal system). Is there a standard (in C++0x) function or functor that will call given std::function? For now I use

std::for_each(c.begin(), c.end(), 
              std::mem_fn(&std::function<void ()>::operator()));

IMHO this std::mem_fn(&std::function<void ()>::operator()) is ugly. I'd like to be able to write

std::for_each(c.begin(), c.end(), funcall);

Is there such a funcall? Alternativly I can implement a function

template<typename I>
void callInSequence(I from, I to)
{
  for (; from != to; ++from) (*from)();
}

Or开发者_如何转开发 may I have to use a signal/slot system, such as Boost::Signals, but I have a feeling that this is an overkill (I do not need multithreading support here, all std::functions are constructed using std::bind).


I'm not aware of any apply function. However, in C++0x you can use lambdas and write the following.

std::for_each(c.begin(), c.end(),
    [](std::function<void ()> const & fn) { fn(); });

Alternatively, you can use the new for loop.

for (auto const & fn: c)
    fn();
0

精彩评论

暂无评论...
验证码 换一张
取 消