mem_fun – funkce
Pomocné funkce šablony použité k vytvoření adaptérů objektu funkce pro členské funkce při inicializaci pomocí argumentů ukazatelů.
template<class Result, class Type>
mem_fun_t<Result, Type> mem_fun (
Result(Type::* _Pm )( )
);
template<class Result, class Type, class Arg>
mem_fun1_t<Result, Type, Arg> mem_fun(
Result (Type::* _Pm )( Arg )
);
template<class Result, class Type>
const_mem_fun_t<Result, Type>
mem_fun(Result (Type::* _Pm )( ) const
);
template<class Result, class Type, class Arg>
const_mem_fun1_t<Result, Type, Arg>
mem_fun(Result (Type::* _Pm )( Arg ) const
);
Parametry
- _Pm
Ukazatel na členské funkce třídy typu převést na objekt funkce.
Vrácená hodnota
A b nebo non_const funkce objekt typu mem_fun_t nebo mem_fun1_t.
Příklad
// functional_mem_fun.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
class StoreVals
{
int val;
public:
StoreVals() { val = 0; }
StoreVals(int j) { val = j; }
bool display() { cout << val << " "; return true; }
int squareval() { val *= val; return val; }
int lessconst(int k) {val -= k; return val; }
};
int main( )
{
vector<StoreVals *> v1;
StoreVals sv1(5);
v1.push_back(&sv1);
StoreVals sv2(10);
v1.push_back(&sv2);
StoreVals sv3(15);
v1.push_back(&sv3);
StoreVals sv4(20);
v1.push_back(&sv4);
StoreVals sv5(25);
v1.push_back(&sv5);
cout << "The original values stored are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
// Use of mem_fun calling member function through a pointer
// square each value in the vector using squareval ()
for_each(v1.begin(), v1.end(), mem_fun<int, StoreVals>(&StoreVals::squareval));
cout << "The squared values are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
// Use of mem_fun1 calling member function through a pointer
// subtract 5 from each value in the vector using lessconst ()
for_each(v1.begin(), v1.end(),
bind2nd (mem_fun1<int, StoreVals,int>(&StoreVals::lessconst), 5));
cout << "The squared values less 5 are: " ;
for_each(v1.begin(), v1.end(), mem_fun<bool, StoreVals>(&StoreVals::display));
cout << endl;
}
Výsledek
The original values stored are: 5 10 15 20 25
The squared values are: 25 100 225 400 625
The squared values less 5 are: 20 95 220 395 620
Požadavky
Záhlaví: <functional>
Obor názvů: std