std::mem_fn
和std::mem_fun
(deprecated)
Convert member function to function object,即将成员函数转化为函数对象,这样就可以像普通函数那样使用。
示例一:
#include <iostream> // std::cout
#include <functional> // std::mem_fnstruct int_holder {int value;int triple() { return value * 3; }
};int main() {int_holder five{ 5 };// call member directly:std::cout << five.triple() << '\n';// same as above using a mem_fn:auto triple = std::mem_fn(&int_holder::triple);std::cout << triple(five) << '\n';
}
示例二:
template<class T>class Fraction {public:Fraction():Fraction(0,1) {std::cout << "Fraction default-ctor called.\n";}Fraction(T num, T den):numerator_(num), denominator_(den) {std::cout << "Fraction ctor called.\n";}virtual ~Fraction() {std::cout << "Fraction dtor called.\n";}T getNumerator() {return numerator_;}T getDenominator() {return denominator_;}template<class U>U calculateValue();private:T numerator_;T denominator_;};template<class T>template<class U>U Fraction<T>::calculateValue() {return static_cast<U>(numerator_) / static_cast<U>(denominator_);}auto main()->void {Fraction<float> fra1(3.f, 5.f);double val1 = fra1.calculateValue<double>();std::cout << val1 << std::endl; // 0.6auto memfunc1 = std::mem_fn(&Fraction<float>::calculateValue<double>);std::cout << memfunc1(fra1) << std::endl; // 0.6}