[英]Understanding std::function and std::bind
我正在玩std :: function和std :: bind,我注意到一些不直觀的東西,我想更好地理解它。
例如:
void fun()
{
}
void hun(std::string)
{
}
int main()
{
function<void(int)> g = &fun; //This fails as it should in my understanding.
function<void(int)> f = std::bind(fun); //This works for reasons unknown to me
function<void(int, std::string)> h = std::bind(hun); //this doesn't work
return 0;
}
它是如何可以將綁定function<void(int)>
到一個函數,是無效的()。 然后我可以調用f(1)並獲得樂趣()。 我想了解這是如何完成的。 進入Microsoft Visual Studio 2012的實現,讓我迷失在無法理解的宏海中。 所以這就是我在這里問這個問題的原因。
如果不使用參數占位符( _1
, _2
,...),那么傳遞給從std::bind
返回的函數對象的任何參數都將被丟棄。 附:
std::function<void(int)> f = std::bind(fun, std::placeholders::_1);
我得到了一個(長而丑陋的)錯誤。
對於對Standardese感興趣的人:
§20.8.9.1.2 [func.bind.bind]
template<class F, class... BoundArgs>
*unspecified* bind(F&& f, BoundArgs&&... bound_args);
p3返回:具有弱結果類型(20.8.2)的轉發調用包裝器
g
。g(u1, u2, ..., uM)
應為INVOKE(fd, v1, v2, ..., vN, result_of<FD cv (V1, V2, ..., VN)>::type)
,其中cv表示g
的cv-限定符 , 並且綁定參數v1, v2, ..., vN
的值和類型如下所述確定 。p10綁定參數
v1, v2, ..., vN
及其對應類型V1, V2, ..., VN
取決於從bind
調用派生的TiD
類型和調用包裝器的cv -qualifiers cvg
如下:
- 如果
TiD
是reference_wrapper<T>
,則參數為tid.get()
,其類型Vi
為T&
;- 如果
is_bind_expression<TiD>::value
值為true
,則參數為tid(std::forward<Uj>(uj)...)
,其類型Vi
為result_of<TiD cv (Uj...)>::type
;- 如果
is_placeholder<TiD>::value
的值j
不為零,則參數為std::forward<Uj>(uj)
,其類型Vi
為Uj&&
;- 否則,該值為
tid
,其類型Vi
為TiD cv &
。
通過調用函數模板bind
生成的轉發調用包裝器可以接受任意數量的額外參數; 這些都會被忽略。 bind
表達式的有效arity和最小簽名由其構造中使用的placeholder
以及它們綁定的可調用參數確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.