[英]how boost::function and boost::bind work
我不喜歡在我的代碼中散布着魔術盒......這兩個類究竟是如何工作的,基本上允許任何函數映射到函數對象,即使函數<>具有完全不同的參數設置為傳遞給我的一個boost::bind
它甚至適用於不同的調用約定(即成員方法在VC下是__thiscall
,但“普通”函數通常是__cdecl
或__stdcall
用於需要與C兼容的那些)。
boost::function
允許將帶有正確簽名的operator()
任何內容綁定為參數,並且可以使用參數int
調用bind的結果,因此可以綁定到function<void(int)>
。
這是它的工作原理(這個描述適用於std::function
):
boost::bind(&klass::member, instance, 0, _1)
返回一個這樣的對象
struct unspecified_type
{
... some members ...
return_type operator()(int i) const { return instance->*&klass::member(0, i);
}
從klass::member
的簽名推斷出return_type
和int
,並且函數指針和bound參數實際上存儲在對象中,但這並不重要
現在, boost::function
不進行任何類型檢查:它將獲取您在其template參數中提供的任何對象和任何簽名,並創建一個可根據您的簽名調用並調用該對象的對象。 如果這是不可能的,那就是編譯錯誤。
boost::function
實際上是一個這樣的對象:
template <class Sig>
class function
{
function_impl<Sig>* f;
public:
return_type operator()(argument_type arg0) const { return (*f)(arg0); }
};
其中return_type
和argument_type
是從Sig
中提取的, f
是在堆上動態分配的。 這需要允許具有不同大小的完全不相關的對象綁定到boost::function
。
function_impl
只是一個抽象類
template <class Sig>
class function_impl
{
public:
virtual return_type operator()(argument_type arg0) const=0;
};
完成所有工作的類是從boost::function
派生的具體類。 對於boost::function
,每種類型的對象都有一個
template <class Sig, class Object>
class function_impl_concrete : public function_impl<Sig>
{
Object o
public:
virtual return_type operator()(argument_type arg0) const=0 { return o(arg0); }
};
這意味着在你的情況下,賦值為boost函數:
function_impl_concrete<void(int), unspecified_type>
(當然是編譯時) 當您調用函數對象時,它會調用其實現對象的虛函數,該函數會將調用指向您的原始函數。
免責聲明:請注意,本說明中的名稱是故意彌補的。 與真人或人物有任何相似之處......你知道嗎。 目的是說明原則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.