Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

mem_fun

类模板  <functional>

template <class S, class T> mem_fun_t<S,T> mem_fun (S (T::*f)());
template <class S, class T, class A> mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A));
template <class S, class T> const_mem_fun_t<S,T> mem_fun (S (T::*f)() const);
template <class S, class T, class A> const_mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A) const);

将成员函数转换为函数对象(指针版本)
返回一个函数对象,该对象封装了类型t的成员函数f。该成员函数返回一个类型S的值,并且可以选择接受一个类型a的形参。

该函数返回的函数对象需要一个指向对象的指针作为operator()的(第一个)参数。 类似的函数,mem_fun_ref生成相同的函数,但会将对象的引用作为(第一个)参数。

函数对象是其类定义成员函数operator()的对象。该成员函数允许使用与常规函数调用相同的语法来使用对象。 一些标准算法和适配器被设计用于函数对象。

它的行为定义如下:
template <class S, class T> mem_fun_t<S,T> mem_fun (S (T::*f)())
{ return mem_fun_t<S,T>(f); }

template <class S, class T, class A> mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A))
{ return mem_fun1_t<S,T,A>(f); }

template <class S, class T> const_mem_fun_t<S,T> mem_fun (S (T::*f)() const)
{ return const_mem_fun_t<S,T>(f); }

template <class S, class T, class A> const_mem_fun1_t<S,T,A> mem_fun (S (T::*f)(A) const)
{ return const_mem_fun1_t<S,T,A>(f); }

☲  模板参数


S
成员函数的返回类型。

T
成员函数是其成员的类型(class)。

A
成员函数接受的参数的类型(如果有)。

☲  参数


f
指向成员函数的指针,接受一个(a类型)实参或不带实参,返回S类型的值。

☉  返回值



调用对象的成员函数f的函数对象,该对象的指针作为(第一个)参数传递。
如果成员函数接受一个形参,则将其指定为函数对象中的第二个实参

☣  示例



// mem_fun example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main () {
  vector <string*> numbers;

  // populate vector of pointers:
  numbers.push_back ( new string ("one") );
  numbers.push_back ( new string ("two") );
  numbers.push_back ( new string ("three") );
  numbers.push_back ( new string ("four") );
  numbers.push_back ( new string ("five") );

  vector <int> lengths ( numbers.size() );

  transform (numbers.begin(), numbers.end(), lengths.begin(), mem_fun(&string::length));

  for (int i=0; i<5; i++) {
    cout << *numbers[i] << " has " << lengths[i] << " letters.\n";
  }

  // deallocate strings:
  for (vector<string*>::iterator it = numbers.begin(); it!=numbers.end(); ++it)
    delete *it;

  return 0;
}

输出:
one has 3 letters.
two has 3 letters.
three has 5 letters.
four has 4 letters.
five has 4 letters.

🍄  另请参阅



ptr_fun 将函数指针转换为函数对象(类模板)
mem_fun_ref 将成员函数转换为函数对象(引用版本)(类模板)
unary_function 一元函数对象基类 (类模板)
binary_function 二元函数对象基类 (类模板)

联系我们 免责声明 关于CandCplus 网站地图