Please help make this boost::bind example compile
Hello, In the code below, the last function, "GetFunctionThatReturnsRefX_2", does not compile. It is attempting to use boost::bind to produce a boost::function that takes a pointer to an object and returns one of the object's member variables by reference. If it is possible, would you modify it so that it does compile? Note 1: No problem when returning a copy as in "GetFunctionThatReturnsCopyX_2" Note 2: I employ a workaround in "GetFunctionThatReturnsRefX_1" that uses a helper "facade" function. I'm hoping to avoid this. Similarly I'm hoping to not have to add member function TCObject::GetX. Invoked with "g++ -c test.cpp" using gcc 4.6.3. Thank you, Chris #include <boost/bind.hpp> #include <boost/function.hpp> //------------------------------------ //------------------------------------ struct TCObject { int x; }; //------------------------------------ //------------------------------------ int GetCopyX(TCObject* pClass) { return pClass->x; } //------------------------------------ //------------------------------------ boost::function<int(TCObject*)> GetFunctionThatReturnsCopyX_1() { return boost::bind(GetCopyX, _1); } //------------------------------------ //------------------------------------ boost::function<int(TCObject*)> GetFunctionThatReturnsCopyX_2() { return boost::bind(&TCObject::x, _1); } //------------------------------------ //------------------------------------ int& GetRefX(TCObject* pClass) { return pClass->x; } //------------------------------------ //------------------------------------ boost::function<int&(TCObject*)> GetFunctionThatReturnsRefX_1() { return boost::bind(GetRefX, _1); } //------------------------------------ //------------------------------------ boost::function<int&(TCObject*)> GetFunctionThatReturnsRefX_2() { //return boost::ref(boost::bind(&TCObject::x, _1)); return boost::bind(&TCObject::x, _1); }
On Tue, Feb 26, 2013 at 8:06 PM, Chris Stankevitz <chrisstankevitz@gmail.com> wrote:
boost::function<int&(TCObject*)> GetFunctionThatReturnsRefX_2() { return boost::bind(&TCObject::x, _1); }
Solution: Bind takes a template argument that is the return type when using class members: boost::function<int&(TCObject*)> GetFunctionThatReturnsRefX_2() { return boost::bind<int&>(&TCObject::x, _1); } Chris
participants (1)
-
Chris Stankevitz