简体   繁体   English

关于C ++中的functor

[英]About functor in C++

I try to use for_each to apply a self-defined functor to an array, but I got an error. 我尝试使用for_each将自定义的仿函数应用于数组,但是我收到了一个错误。

template< class T> 
class add{
public:
bool operator() (T& a, T& b) const{
a+=b;
return true;
}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};

void runEx03(){
vector<int> intArray(10);
for(int i=0;i<10;i++)
intArray[i] = i;
int res =0;
for_each(intArray.begin(),intArray.end(),bind2nd(add<int>(),4));
for(int i=0;i<10;i++)
cout << intArray[i]<<endl;
}

It returns an error: 它返回一个错误:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(342): error C2664:    'bool add<T>::operator ()(T &,T &) const' : cannot convert parameter 2 from 'const int' to 'int &'
1>          with
1>          [
1>              T=int
1>          ]
1>          Conversion loses qualifiers
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(341) :     while compiling class template member function 'bool std::binder2nd<_Fn2>::operator ()(int &) const'
1>          with
1>          [
1>              _Fn2=add<int>
1>          ]
1>          d:\study\c06\c06\source.cpp(59) : see reference to class template instantiation 'std::binder2nd<_Fn2>' being compiled
1>          with
1>          [
1>              _Fn2=add<int>
1>          ]

I don't know why it gives this error. 我不知道为什么会出现这个错误。 The code looks all right. 代码看起来很好。

常量4不能绑定到int& (但它可能是const int& ),所以将运算符add为:( bool在这里没用)

void operator() (T& a, const T& b) const { a += b; }

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

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