1

I am learning boost lambda (not c++0X lambda because I guess they are different). But I can't find a way online to call a member function (and then output the result) if the only input parameter is a call object. I mean this line works:

for_each(vecCt.begin(), vecCt.end(), cout<<_1<<endl);

if vecCt is a vector of int. But what if vecCt is a vector of MyClass, which has a function called getName to return a string? Neither this:

for_each(vecCt.begin(), vecCt.end(), cout<<_1->getName());

nor this:

for_each(vecCt.begin(), vecCt.end(), cout<<*_1.getName());

works.

I searched online but many results suggest to use bind when calling member function. Now I know this

for_each(vecCt.begin(), vecCt.end(), bind(&MyClass::getName, _1);

makes me able to call getName on each object passed int, but how can I pass this output to cout? This doesn't work:

for_each(vecCt.begin(), vecCt.end(), cout<<bind(&MyClass::.getName, _1);
sehe
  • 374,641
  • 47
  • 450
  • 633
tete
  • 4,859
  • 11
  • 50
  • 81

1 Answers1

1

Quite likely you're mixing placeholders and functions from boost::, global, boos::lambda (possibly more, like boost::phoenix too).

Here's fixed demo: Live On Coliru

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

struct X
{
    int x;
    std::string accessor() const { return "X[" + std::to_string(x) + "]"; } // I know, requires c++11
};

int main()
{
    std::vector<X> v;
    v.push_back({ 1 });
    v.push_back({2});
    v.push_back({3});
    v.push_back({4});
    v.push_back({5});

    std::for_each(v.begin(), v.end(), 
        std::cout << boost::lambda::bind(&X::accessor, boost::lambda::_1) << "\n");
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Thank you for your reply. I simply get the error "bind is not a member of boost::lambda" (is it a typo, should it be boost::bind?). I compiled using c++ with default standard which I think is c++98. I also tried with c++0x but the same error. And if I tried boost::bind with c++0x, the compile error is different: cannot bind 'std::ostream' lvalue to 'std::basic_ostream' (the original error was no match for 'operator<<') – tete Oct 23 '14 at 14:00
  • 1
    Did you copy the whole sample? If so, you should have gotten either `boost/boost/lambda.hpp` or `boost/lambda/bind.hpp`. Also, if you get that `operator<<` message you're probably still mixing/matching different namespaces. Try with my exact code, edit it until you see what makes your code different – sehe Oct 23 '14 at 14:39