开发者

Problem using bind1st and bind2nd with transform

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&开发者_JAVA技巧, 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜