簡體   English   中英

使用 lambda 作為 C++ 函數的參數

[英]Use a lambda as a parameter for a C++ function

我想使用 lambda 作為 C++ 函數的參數,但我不知道在函數聲明中指定哪種類型。 我想做的是:

void myFunction(WhatToPutHere lambda){
    //some things
}

我試過void myFunction(auto lambda)void myFunction(void lambda)但這些代碼都沒有編譯。 如果重要,lambda 不會返回任何內容。

如何在 C++ 函數中使用 lambda 作為參數?

您有兩種方法:制作您的功能模板:

template <typename F>
void myFunction(F&& lambda)
{
    //some things
}

或擦除類型(例如使用std::function ):

void
myFunction(const std::function<void()/*type of your lamdba::operator()*/>& f)
{
    //some things
}

基本上,你有兩個選擇。

使其成為模板:

template<typename T>
void myFunction(T&& lambda){
}

或者,如果您不想(或不能)這樣做,您可以使用類型擦除的std::function

void myFunction(std::function<void()> const& lambda){
}

相反,在當前在 gcc 中實現的概念 TS 下,您對auto的嘗試是正確的,它是一個縮寫的 template

// hypothetical C++2x code
void myFunction(auto&& lambda){
}

或有一個概念:

// hypothetical C++2x code
void myFunction(Callable&& lambda){
}

如果這是一個inline函數,則更喜歡模板,如

template<typename Func>
void myFunction(Func const&lambda)
{
    //some things
}

因為它綁定到任何有意義的東西(並且會導致其他任何東西的編譯器錯誤),包括 lambda、命名類的實例和std::function<>對象。

另一方面,如果此函數不是inline ,即在某些編譯單元中實現,則不能使用通用模板,而必須使用指定類型,最好采用std::function<>對象並通過引用傳遞。

像傳遞一個簡單的函數一樣傳遞它。 給它一個auto的名字

#include <iostream>

int SimpleFunc(int x) { return x + 100; }
int UsingFunc(int x, int(*ptr)(int)) { return ptr(x); }
auto lambda = [](int jo) { return jo + 10; };

int main() {
    std::cout << "Simple function passed by a pointer: " << UsingFunc(5, SimpleFunc) << std::endl;
    std::cout << "Lambda function passed by a pointer: " << UsingFunc(5, lambda) << std::endl;

}

輸出:
指針傳遞的簡單函數:105
通過指針傳遞的 Lambda 函數:15

暫無
暫無

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

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