I have a vector of callbacks and I'd like to execute them. This is what I do:

typedef boost::function<void (void)> FCallBack;
std::vector<FCallBack> c;
// Execute every callback
std::for_each(c.begin(), c.end(), boost::bind(&FCallBack::operator(), _1));

This works, but is there an easier way to do so? For some reason reference to operator() bothers me. Am I missing something simple?


9 Years
Discussion Span
Last Post by vijayan121

Here's another way to use a vector of function pointers. This uses c-style function pointers, and this could probably be simplified too.

#include <iostream>
#include <vector>
using namespace std;

int a(float x, char b, char c)
    cout << "function a\n";
    return 1;

int b(float x, char b, char c)
    cout << "function b\n";
    return 1;
typedef struct
    int (*fnptr)(float, char, char);

int main()
    Callback fn;
    vector<Callback> FCallBack;
    fn.fnptr = a;
    fn.fnptr = b;
    vector<Callback>::iterator it;
    for(it = FCallBack.begin(); it != FCallBack.end(); it++)
        Callback& cb = *it;
return 0;

Thanks, Ancient Dragon. I see what you mean. I need to rephrase my question :) How do I execute operator() on elements of a vector in an algorithm.

Btw. it++ is less efficient then ++it (so called premature pessimization)


> For some reason reference to operator() bothers me. Am I missing something simple?
one reason why this may be a bother is possible loss of efficiency. a function called via a pointer is usually not inlinable. (what a pointer points to is techically something that is known only at runtime.) perhaps this is a simpler option:

template< typename FN > struct call_it
  typename FN::result_type operator()( const FN& fn ) const
  { return fn() ; }

int main()
  typedef boost::function< void(void) > fn_t ;
  std::vector< fn_t > functions ;
  // ..
  std::for_each( functions.begin(), functions.end(),
                 call_it<fn_t>() ) ;
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.