簡體   English   中英

了解std :: function和std :: bind

[英]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表示gcv-限定符並且綁定參數v1, v2, ..., vN的值和類型如下所述確定

p10綁定參數v1, v2, ..., vN及其對應類型V1, V2, ..., VN 取決於從bind調用派生的TiD類型和調用包裝器的cv -qualifiers cv g如下:

  • 如果TiDreference_wrapper<T> ,則參數為tid.get() ,其類型ViT& ;
  • 如果is_bind_expression<TiD>::value值為true ,則參數為tid(std::forward<Uj>(uj)...) ,其類型Viresult_of<TiD cv (Uj...)>::type ;
  • 如果is_placeholder<TiD>::value的值j不為零,則參數為std::forward<Uj>(uj) ,其類型ViUj&& ;
  • 否則,該值為tid ,其類型ViTiD cv &

通過調用函數模板bind生成的轉發調用包裝器可以接受任意數量的額外參數; 這些都會被忽略。 bind表達式的有效arity和最小簽名由其構造中使用的placeholder以及它們綁定的可調用參數確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM