As explained in the section Member variables as targets:
A pointer to a member variable is not really a function, but the first argument to the [boost::lambda::bind
] function can nevertheless be a pointer to a member variable. Invoking such a bind expression returns a reference to the data member.
So to construct a lambda expression that accesses the z
member, you can use:
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1)
The returned object can itself be used in other expressions. For example,
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0
means "obtain the double
ref to the z
member of the first argument (type Imath::V3f&
) and assign the value 0.0".
You can then use this lambda with Boost.Function and std::for_each
:
boost::function<void(Imath::V3f&)> f = boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0;
std::for_each(vec.begin(), vec.end(), f);
For reference, here is a complete, compilable example:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
namespace Imath
{
class V3f
{
public:
double x, y, z;
V3f(double x_, double y_, double z_)
: x(x_), y(y_), z(z_)
{
}
friend std::ostream& operator<<(std::ostream& os, const V3f& pt) {
return (os << '(' << pt.x << ", " << pt.y << ", " << pt.z << ')');
}
};
}
int main()
{
std::vector<Imath::V3f> vec(5, Imath::V3f(1.0, 1.0, 1.0));
boost::function<void(Imath::V3f&)> f = boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0;
std::for_each(vec.begin(), vec.end(), f);
std::vector<Imath::V3f>::iterator it, end = vec.end();
for (it = vec.begin(); it != end; ++it) {
std::cout << *it << std::endl;
}
return EXIT_SUCCESS;
}
Outputs:
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)