Domanda

#include <vector>
#include <iostream>
#include "boost/function.hpp"


template <class T1, class T2, class T3>
static void
FOREACH (T1 cont, boost::function<T2(T3)> callback) {
    typename T1::iterator it = cont. begin ();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}


static void
Print (int number) 
{
    std:: cout << number << std:: endl;
}


int  main ()
{
    std:: vector<int> vec;
    for ( int i=1; i <= 10; ++i ) vec. push_back (2*i);

    FOREACH ( vec, fun );

    return 0;
}

Why above code does not compile? If I create specialized version like below it works fine.

static void
FOREACH (std:: vector<int> cont, boost::function<void(int)> callback) {
    std:: vector<int>:: iterator it = cont. begin ();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}

Please someone tell me how could I use boost::function with function templates?

È stato utile?

Soluzione

It would be simpler to make the functor a template parameter:

template <class T1, class F>
static void FOREACH (T1 cont, F callback) {
    typename T1::iterator it = cont.begin();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}

This would work, provided you pass it a compatible callable entity that actually exists. Of course, it would be even easier to use std::for_each:

#include <algoritm>

...

std::for_each(vec.begin(), vec.end(), Print);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top