Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using bind1st and bind2nd with transform

Tags:

c++

c++11

stl

I think C++0x bind is much better, but I'd like to understand the old bind1st and 2st before I use C++0x's bind:

struct AAA
{
    int i;
};

struct BBB
{
    int j;
};

// an adaptable functor.
struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
    BBB operator()(const AAA& aaa, int x)
    {
        BBB b;
        b.j = aaa.i * x;
        return b;
    }
};

BBB ConvertFunction(const AAA& aaa, int x)
{
    BBB b;
    b.j = aaa.i * x;
    return b;
}

class BindTest
{
public:
    void f()
    {
        std::vector<AAA> v;
        AAA a;
        a.i = 0;
        v.push_back(a);
        a.i = 1;
        v.push_back(a);
        a.i = 2;
        v.push_back(a);

        // It works.
        std::transform(
            v.begin(), v.end(),
            std::back_inserter(m_bbb),
            std::bind(ConvertFunction, std::placeholders::_1, 100));

        // It works.
        std::transform(
            v.begin(), v.end(),
            std::back_inserter(m_bbb),
            std::bind(ConvertFunctor(), std::placeholders::_1, 100));

        // It doesn't compile. Why? How do I fix this code to work?
        std::transform(
            v.begin(), v.end(),
            std::back_inserter(m_bbb),
            std::bind2nd(ConvertFunctor(), 100));

        std::for_each(m_bbb.begin(), m_bbb.end(),
            [](const BBB& x){ printf("%d\n", x.j); });
    }

private:
    std::vector<BBB> m_bbb;
};

int _tmain(int argc, _TCHAR* argv[])
{
    BindTest bt;
    bt.f();
}

Why can't the third transform function be compiled? How do I fix this code to work?

like image 642
Benjamin Avatar asked Sep 23 '26 04:09

Benjamin


1 Answers

Change

struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
    BBB operator()(const AAA& aaa, int x)
    {

to:

struct ConvertFunctor : std::binary_function<AAA, int, BBB>
{
    BBB operator()(const AAA& aaa, int x) const
    {

Don't ask me why, I only read the compilation error messages.

like image 106
Luc Danton Avatar answered Sep 25 '26 17:09

Luc Danton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!