[英]How to pass a rvalue reference parameter to a template operator() function in C++?
[英]How to pass a c++ functor rvalue reference to a capture of a lambda ?
我有以下功能
template<class Function>
void f(Function&& g) {
h(..., [&g](){g();});
}
它是一個函數f
接受功能,一個lambda或仿函數作為參數。 在它內部調用函數h
,我將一個lambda作為參數傳遞給該函數,該函數調用g
並通過捕獲接收g
。
g
或&g
嗎? 如果您通過引用捕獲g
,即使用代碼段中顯示的語法&g
,將不會執行任何復制。 這是首選方式。 僅當f
完成后可能調用lambda時才應復制,這可能意味着g
引用的對象被破壞。
在這種情況下,轉發可能會更便宜:
template<class Function>
void f(Function&& g) {
h(…, [g=std::forward<Function>(g)] {g();});
}
您正在構造一個不接受任何參數且不返回任何內容的lambda。 但是您已經有了這樣的函子: g
!。 您應該轉發它:
template<class Function>
void f(Function&& g) {
h(..., std::forward<Function>(g));
}
您可以這樣做:
template<class Function>
void f(Function&& g) {
Function f(std::move(g));
int additional = 0;
h(..., [&f, additional](){f(additional);});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.