C++ 使用带转换的bind1st和bind2nd时出现问题
我认为C++0x绑定要好得多,但在使用C++0x绑定之前,我想先了解旧的bind1st和2st:C++ 使用带转换的bind1st和bind2nd时出现问题,c++,stl,c++11,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, in
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();
}
struct-AAA
{
int i;
};
结构BBB
{
int j;
};
//适应性函子。
结构转换函数:std::binary_函数
{
BBB运算符()(常数AAA和AAA,整数x)
{
BBB;
b、 j=aaa.i*x;
返回b;
}
};
BBB转换函数(常数AAA和AAA,整数x)
{
BBB;
b、 j=aaa.i*x;
返回b;
}
类绑定测试
{
公众:
void f()
{
std::向量v;
AAA a;
a、 i=0;
v、 推回(a);
a、 i=1;
v、 推回(a);
a、 i=2;
v、 推回(a);
//它起作用了。
std::transform(
v、 开始(),v.结束(),
标准:背面插入器(m_bbb),
std::bind(ConvertFunction,std::占位符::_1100));
//它起作用了。
std::transform(
v、 开始(),v.结束(),
标准:背面插入器(m_bbb),
std::bind(ConvertFunctor(),std::占位符::\u 1100));
//它无法编译。为什么?如何修复此代码以使其正常工作?
std::transform(
v、 开始(),v.结束(),
标准:背面插入器(m_bbb),
std::bind2nd(ConvertFunctor(),100));
std::for_each(m_bbb.begin(),m_bbb.end(),
[](constbbb&x){printf(“%d\n”,x.j);});
}
私人:
std::向量m_bbb;
};
int _tmain(int argc,_TCHAR*argv[]
{
结合剂试验;
bt.f();
}
为什么不能编译第三个转换函数?如何修复此代码以使其正常工作?更改
struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
BBB operator()(const AAA& aaa, int x)
{
struct ConvertFunctor:std::binary_函数
{
BBB运算符()(常数AAA和AAA,整数x)
{
致:
struct ConvertFunctor:std::binary_函数
{
BBB运算符()(常数AAA和AAA,整数x)常数
{
不要问我为什么,我只读了编译错误消息。我相信原因是std::binder2nd通过const&获取所有参数,并且不能有一个const&到一个const&。原因是C++03没有完美的转发,所以const&是最好的默认值(大概,C++0x的std::bind使用右值引用,所以这不是问题)。要给出引用,bind2nd的操作符()是
typename操作::result\u type操作符()(const typename操作::first\u参数\u type&x)const;
,它返回op(x,value)
(根据C++03的20.3.6.3[lib.binder.2nd]),其中,op
和value
是函子和绑定参数的副本。对于const
在operator()
的声明中,这是因为bind2nd
用const&
捕捉对象ConvertFunctor
,因此必须使函数被调用operator()
const。
struct ConvertFunctor : std::binary_function<AAA, int, BBB>
{
BBB operator()(const AAA& aaa, int x) const
{