在转换中使用bind1st和bind2nd的问题

Problem using bind1st and bind2nd with transform

本文关键字:bind2nd 问题 bind1st 转换      更新时间:2023-10-16

我认为c++ 0x绑定要好得多,但在我使用c++ 0x的bind:

之前,我想了解旧的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("%dn", x.j); });
    }
private:
    std::vector<BBB> m_bbb;
};
int _tmain(int argc, _TCHAR* argv[])
{
    BindTest bt;
    bt.f();
}

为什么不能编译第三个转换函数?我如何修复这个代码的工作?

变化

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
    {

不要问我为什么,我只看编译错误信息