0
我嘗試使用boost :: bind創建一個函數對象,我也想將一個在HEAP上創建的對象綁定到它爲延遲呼叫。示例代碼如下所示:使用boost :: bind創建綁定自動釋放「heap」資源的函數對象
#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()> 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;
}
以上只是一個示例代碼。但我認爲它顯示了我想要的和當前的錯誤。
目前,我想我只能用一個函數對象來包裝原函數象下面這樣:
class CGetM
{
public:
typedef int result_type;
int operator() (shared_ptr<CTest> t)
{
return getM(t.get());
}
};
而更換這樣的代碼:
return bind<int>(CGetM() , a);
但是,如果目前我有許多像getM這樣的原始函數,用於調整正確的參數,將其封裝在函數對象中確實是一項大工作。我不知道在boost中是否有某種提示或其他有用的util類可以更智能和更優雅地處理這種情況?
所以,任何建議表示讚賞。謝謝。
我測試,這是偉大的!我不知道綁定可以用這種方式使用,看起來像foo(),bar(),最後成爲foo(bar()),這很有趣。 – winterTTr