简体   繁体   English

将 bind1st 和 bind2nd 与变换一起使用时出现问题

[英]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:我认为 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();
}

Why can't the third transform function be compiled?为什么第三次变换function编译不出来? 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.不要问我为什么,我只看了编译错误信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM