Hello,
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?

Thanks.

Recommended Answers

All 4 Replies

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);
}Callback;


int main()
{
    Callback fn;
    vector<Callback> FCallBack;
    fn.fnptr = a;
    FCallBack.push_back(fn);
    fn.fnptr = b;
    FCallBack.push_back(fn);
    vector<Callback>::iterator it;
    for(it = FCallBack.begin(); it != FCallBack.end(); it++)
    {
        Callback& cb = *it;
        cb.fnptr(0,'A','B');
    }
    
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)

I'm probably not the best person to answer your question because I have used boost very little.

> 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>() ) ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.