Phong
Phong

Reputation: 6768

How to use std::for_each on a function pointer list

On the following code, how can i rewrite the for loop by using a std::for_each instruction. I tried to use boost::lambda::_1, boost::bind, but I could not make it working.

#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>

int main() 
{ 
  std::vector<int(*)(const char*)> processors; 
  processors.push_back(std::atoi); 
  processors.push_back(reinterpret_cast<int(*)(const char*)>(std::strlen)); 

  const char data[] = "1.23"; 

  for(std::vector<int(*)(const char*)>::iterator it = processors.begin();
      it != processors.end(); ++it) 
    std::cout << (*it)(data) << std::endl;
}

Any hint to help me solve this problem are welcome.

EDIT: Solution

#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

int main() 
{ 
  std::vector<boost::function<int(const char*)> > processors; 
  processors.push_back(std::atoi); 
  processors.push_back(std::strlen); 

  const char data[] = "1.23"; 

  namespace bl = boost::lambda;
  std::for_each(processors.begin(), processors.end(),
      std::cout << bl::bind(bl::_1, data) << "\n");
}

Upvotes: 3

Views: 1395

Answers (3)

Ise Wisteria
Ise Wisteria

Reputation: 11669

If boost::lambda and '\n' instead of endl are allowed, does the following code meet the purpose?

namespace bl = boost::lambda;
std::for_each( processors.begin(), processors.end()
             , std::cout << bl::bind( bl::_1, data ) << '\n' );

Upvotes: 2

Emile Cormier
Emile Cormier

Reputation: 29209

You might find it easier to use BOOST_FOREACH:

#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <boost/foreach.hpp>
#include <boost/function.hpp>

int main()
{
    typedef boost::function<int(const char*)> ProcessorFunc;
    std::vector<ProcessorFunc> processors;
    processors.push_back(std::atoi);
    processors.push_back(std::strlen);

    const char data[] = "1.23";

    BOOST_FOREACH(ProcessorFunc& proc, processors)
    {
        std::cout << proc(data) << std::endl;
    }

}

Or you could use a ranged-based for loop from C++0x.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

void blah(int (*func)(const char *), const char *data)
{
    std::cout << func(data) << std::endl;
};

...

std::for_each(processors.begin(), processors.end(), boost::bind(blah, _1, data));

Upvotes: 1

Related Questions