简体   繁体   中英

Boost lambda function call

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM