Using boost::bind to create a function object binding a auto-release "heap" resource
I try to use boost::bind to create a function object, as well, I want to bind a object created on the HEAP to it for a delay call. The example code like below:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>
using namespace boost;
class CTest : public noncopyable
{
public:
CTest():mInt(0){ std::cout << "constructor" << std::endl; }
~CTest(){ std::cout << "destructor" << std::endl; }
int mInt;
};
int getM( CTest * t )
{
return t->mInt;
}
function<int()>开发者_JAVA百科 makeF()
{
// create some resource on HEAP, not on STACK.
// cause the STACK resource will be release after
// function return.
BOOST_AUTO( a , make_shared<CTest>() );
// I want to use bind to create a function call
// wrap the original function and the resource I create
// for delay call.
//
// I use shared_ptr to auto release the resource when
// the function object is gone.
//
// Compile ERROR!!!
// cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'CTest *'
//
return bind<int>( getM , a );
}
int main(int argc, char* argv[])
{
BOOST_AUTO( delayFunc , makeF() );
delayFunc();
return 0;
}
The above is just a example code. But I think it shows what I want and the current error is.
Currently, I think I can only use a function object to wrap the original function like below:
class CGetM
{
public:
typedef int result_type;
int operator() ( shared_ptr<CTest> t )
{
return getM( t.get() );
}
};
And replace the code like this:
return bind<int>( CGetM() , a );
However, if currently I have many original function like getM, for adapting the correct arguments, wrapping it in a function object is really a large job. I don't know if there is some kind of tips or other useful util class in boost can handle such case more intelligently and elegantly ?
So any suggestion is appreciated. Thanks.
You need to use bind composition:
return bind<int>( getM, bind(&shared_ptr<CTest>::get, a) );
精彩评论