Boost logo

Boost Users :

Subject: [Boost-users] Please help make this boost::bind example compile
From: Chris Stankevitz (chrisstankevitz_at_[hidden])
Date: 2013-02-26 23:06:28


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);
}


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