簡體   English   中英

如何將可變數量的參數傳遞給lambda函數

[英]How to pass variable number of arguments to lambda function

我試圖將可變數量的參數傳遞給lambda函數。 在lambda函數中接受可變數量參數的原型是什么? 我應該寫一個命名函數而不是lambda嗎?

std::once_flag flag;

template<typename ...Args>
void gFunc(Args... args)
{
}

template<typename ...Args>
void func(Args... args)
{
    std::call_once(flag,[](/*accept variable number of arguments*/... args)
                        {
                                // more code here
                                gFunc( args...);
                        }, 
                        args...
                        );
}

以下簽名給出錯誤:

[&](){ }
[&args](){ }
[&args...](){ }
[&,args...](){ }
[&...args](){ }

在C ++ 14中,你可以做到

auto lambda = [](auto... args) {...};

但在你的情況下,我相信簡單的捕獲就足夠了:

std::call_once(flag, [&] {
                         gFunc(args...); // will implicitly capture all args
                     }
               );

試試這個 :

template<typename ...Args>
void func(Args... args)
{
    std::call_once(flag,[&, args...]( )
                        {   
                         gFunc( args...);
                        }, 
                        args...
                        );
}

這里偷來

§5.1.2捕獲后跟省略號是包擴展(14.5.3)。

[ Example:
template<class... Args>
void f(Args... args) {
auto lm = [&, args...] { return g(args...); };
lm();
}
—end example ]

暫無
暫無

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

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