[英]Alias Declarations in C++
我遇到了這個代碼片段,不知道這意味着什么:
#include <iostream>
int main(){
using test = int(int a, int b);
return 0;
}
我猜想可以用test
代替int(int a, int b)
,但是int(int a, int b)
到底是什么意思? 是功能嗎? 如何使用?
int(int a, int b)
是一個函數聲明,具有兩個類型為int
且返回類型也為int
。
您可以將此別名聲明用作例如類的成員函數聲明,或在參數聲明中使用它。
它是函數簽名的別名。
更完整的用法是聲明函數的指針或引用
int foo(int, int);
int main()
{
using test = int(int a, int b); // identifiers a and b are optional
test *fp = &foo;
test *fp2 = foo; // since the name of function is implicitly converted to a pointer
test &fr = foo;
test foo; // another declaration of foo, local to the function
fp(1,2); // will call foo(1,2)
fp2(3,4); // will call foo(3,4)
fr(5,6); // will call foo(5,6)
foo(7,8);
}
只是為了給該行提供另一個使用選項,帶有lambda表達式:
int main() {
using test = int(int, int);
test le = [](int a, int b) -> int {
return a + b;
}
return 0;
}
關於測試的使用,您必須記住一點,可能有更有效的方法來聲明函數簽名,例如在lambda表達式中使用auto
,在將函數作為參數傳遞給另一個函數的情況下使用template
,等等。
這種方式完全來自純C編程,並帶有using
。 我不建議您選擇這種方式,但是對於一般的理解,了解更多的知識總是比正確的方法更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.