I try to use for_each to apply a self-defined functor to an array, but I got an error.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.