Reputation: 5019
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);
Upvotes: 1
Views: 1252
Reputation: 393769
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");
}
Upvotes: 1