[英]Why can a C++ function type alias be used to pass a lambda to a function?
看看下面列出的代碼示例,我使用編譯器資源管理器(使用 gcc 和 clang)對其進行了測試,它可以工作並打印出(預期的)200 的 output。
我想弄清楚的是:為什么這個有效的C++。 或者不是嗎?
Here, I'm using the using
keyword to define an alias (instead of a typedef
) for the function type ft
, which describes functions that take an int
as argument and return an int
( ft
is a function type, not a function pointer type .) 等效的typedef
語法是typedef int ft(int);
. 由於 C++ 標准說對於每個typedef
都有一個使用using
語法的等效形式,很明顯using ft = int(int)
是指定此 function 類型的明確定義的方法。
現在到了有趣的部分:我使用類型ft
指定另一個 function ( print_it
) 的參數類型,然后調用它,傳遞一個 lambda ZC1C425268E68385D1AB5074C17A9。 我的問題是:C++ 標准在哪里/如何說這實際上應該起作用? 我認為這是一種非常簡單的傳遞 lambda 的方法。 我不清楚這是否有效,因為 lambda 確實是一個函子,而不是嚴格意義上的 function。 因此,我認為尚不清楚此 lambda 是否與ft
類型匹配,因此可以傳遞給print_it
(如果ft
被定義為std::function<int(int)>
它會很清楚)。
代碼示例:
#include <iostream>
using ft = int(int);
void print_it (ft f, int a)
{
std::cout << f(a) << std::endl;
}
int main ()
{
auto my_lambda = [] (int a) -> int { return 2 * a; };
print_it (my_lambda, 100);
return (0);
}
我的問題是:C++ 標准在哪里/如何說這實際上應該起作用?
This is specified in [expr.prim.lambda.closure]/7 , which specifies that a lambda's closure type has a conversion function to a function pointer type matching the lambda's parameter and return types if the lambda is non-generic and doesn't有任何捕獲。 Calling through this function pointer basically behaves as if the lambda body was just a normal function to which the pointer points, which is possible because there are no captures which could give the lambda a state that a normal function can't have.
這適用於此處,並且您正在使用轉換運算符將 lambda object 隱式轉換為 function 指針,然后將其傳遞給print_it
。 這是有效的,因為 lambda 的參數和返回類型與ft
類型匹配,並且用作 function 參數類型的 function 類型被調整為指向函數的類型。 (最后一部分參見[dcl.fct]/5 。)
對於通用 lambda,有一個轉換 function 模板(參見以下標准段落)。 對於帶有捕獲的 lambda,沒有這樣的轉換 function,因此這對他們不起作用。
這僅適用於您的 lambda 不捕獲。 無捕獲的 lambda 可以轉換為 C 樣式的 function 指針,但捕獲的 lambda 不能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.