我遇到了这个代码片段,但不知道它是什么意思:
#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
转折。我不建议选择这种方式,但为了一般理解,知道比正确方式更多总是好的。