关于C ++中的functor

时间:2014-02-26 13:35:49

标签: c++ visual-studio-2010

我尝试使用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;
}

它返回错误:

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>          ]

我不知道为什么会出现这个错误。代码看起来很好。

1 个答案:

答案 0 :(得分:2)

常量4无法绑定到int&(但它可以绑定到const int&),因此将add中的运算符更改为:(bool在这里没用)

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