Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) std::mem_fun_ref

 

An adapter to be able to use for_each on a method of T stored in a container as T (compare std::mem_fun, to use for_each on a method of T stored in a container as T* ).

Example

 

 

#include <iostream>

#include <algorithm>

#include <vector>

 

struct HelloWorld

{

void operator()() const { std::cout << "Hello world" << std::endl; }

};

 

int main()

{

std::vector<HelloWorld> v(10);

std::for_each(v.begin(), v.end(), std::mem_fun_ref(&HelloWorld::operator()));

}

 

 

Replacing a for loop by algorithms using std::mem_fun_ref

 

 

#include <vector>

 

struct Widget

{

void DoIt() const { /* do it */ }

};

 

void DoIt(const std::vector<Widget>& v)

{

const int sz = v.size();

for (int i=0; i!=sz; ++i)

{

v[i].DoIt();

}

}

 

 

 

 

#include <vector>

#include <algorithm>

#include <numeric>

 

struct Widget

{

void DoIt() const { /* do it */ }

};

 

void DoIt(const std::vector<Widget>& v)

{

std::for_each(v.begin(),v.end(),std::mem_fun_ref(&Widget::DoIt));

}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.