今天研究模板,巧遇一个疑问。 仿函数,如果要能被bind2nd之类的适配器配接,要从binary_function或unary_function派生,并且operator() 必须const,如果operator被const的话,怎么来实现一个内部有状态而且又能被配接的仿函数呢,例程如下: template <typename T> class FindNumb//: public std::binary_function <T, T, T> { public: FindNumb():counter(0){}; FindNumb(const T& ict):counter(ict){}; T operator()(const T& i, const T& num)// const { counter++; //如果即要改变functor内部状态,就必须放弃上面的const,但放弃const就不能被bind2nd配接,否则编译错误 return i + num; } private: T counter; };
解决方法是mutable
template <typename T> class FindNumb//: public std::binary_function <T, T, T> { public: FindNumb():counter(0){}; FindNumb(const T& ict):counter(ict){}; T operator()(const T& i, const T& num)// const { counter++; //如果即要改变functor内部状态,就必须放弃上面的const,但放弃const就不能被bind2nd配接,否则编译错误 return i + num; } private: mutable T counter; };