gpt4 book ai didi

c++ - 将 bind1st 和 bind2nd 与转换一起使用时出现问题

转载 作者:太空狗 更新时间:2023-10-29 20:46:58 28 4
gpt4 key购买 nike

我认为 C++0x 的绑定(bind)要好得多,但我想在使用 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("%d\n", x.j); });
}

private:
std::vector<BBB> m_bbb;
};

int _tmain(int argc, _TCHAR* argv[])
{
BindTest bt;
bt.f();
}

为什么第三个transform函数编译不出来?如何修复此代码以使其正常工作?

最佳答案

改变

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
{

别问我为什么,我只看编译错误信息。

关于c++ - 将 bind1st 和 bind2nd 与转换一起使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6736015/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com