使用bind1st和bind2nd与transform的问题

Ben*_*min 3 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();
}
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*ton 5

更改

struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
    BBB operator()(const AAA& aaa, int x)
    {
Run Code Online (Sandbox Code Playgroud)

至:

struct ConvertFunctor : std::binary_function<AAA, int, BBB>
{
    BBB operator()(const AAA& aaa, int x) const
    {
Run Code Online (Sandbox Code Playgroud)

不要问我为什么,我只读取编译错误信息.

  • 我相信原因是因为std :: binder2nd通过const&获取所有参数,并且你不能有const&到const&.原因是因为C++ 03没有完美的转发,所以const&是最好的默认值(推测,C++ 0x的std :: bind使用rvalue引用,因此它不是问题). (2认同)
  • 为了给出引用,bind2nd的operator()是`typename Operation :: result_type operator()(const typename Operation :: first_argument_type&x)const;`返回`op(x,value)`(根据C++ 03的20.3.6.3) [lib.binder.2nd]),其中`op`和`value`是仿函数和绑定参数的副本. (2认同)