Boost logo

Boost Users :

From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2006-03-14 04:12:50


On 3/14/06, Rob Caldecott <robert.caldecott_at_[hidden]> wrote:
> Greetings,
>
> Is it possible to use boost::bind in a for_each loop to call a member of the
> class that is making the call? For example:
>
> class CTest
> {
> public:
> void SomeFunc(const std::wstring& str) const
> {
> // Do something with str
> }
>
> void DoSomething() const
> {
> std::vector<std::wstring> v;
> v.push_back(L"test");
> ...
> for_each(v.begin(), v.end(), bind(&CTest::SomeFunc, _1));
> }
> };
>
> Obviously the above will not compile - and I'm pretty sure that somewhere in
> the bind, "this" will need to be passed, but I am struggling to make this
> work. I know I could use a static member function or use a function object
> and pass it "this", but I wondered if there is a way to cut out the
> middle-man and call a member function directly in this way?
>

You certainly can - add 'this' as the first bound parameter, like so:

for_each(v.begin(), v.end(), bind(&CTest::SomeFunc, this, _1));

HTH
Stuart Dootson


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net