セクションターゲットとしてのメンバー変数で説明されているように:
メンバー変数へのポインターは実際には関数ではありませんが、[ ] 関数の最初の引数boost::lambda::bind
はメンバー変数へのポインターになることができます。このようなバインド式を呼び出すと、データ メンバーへの参照が返されます。
したがって、z
メンバーにアクセスするラムダ式を作成するには、次を使用できます。
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1)
返されたオブジェクト自体を他の式で使用できます。例えば、
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0
は、「最初の引数 ( type )double
のメンバーへの参照を取得し、値 0.0 を割り当てる」ことを意味します。z
Imath::V3f&
次に、このラムダを Boost.Function および で使用できます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);
参考までに、コンパイル可能な完全な例を次に示します。
#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;
}
出力:
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)