使用bind1st和bind2nd与transform的问题

时间:2011-07-18 16:21:33

标签: c++ stl c++11

我认为C ++ 0x绑定要好得多,但我想在使用C ++ 0x绑定之前理解旧的bind1st和2st:

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

为什么不能编译第三个转换函数?如何修复此代码?

1 个答案:

答案 0 :(得分:5)

更改

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

为:

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

不要问我为什么,我只阅读编译错误消息。