C++中的别名声明
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
转折。我不建议选择这种方式,但为了一般理解,知道比正确方式更多总是好的。
相关文章:
- C++使用默认模板参数键入别名和转发声明
- 为什么别名声明不是有效的 init 语句(/simple-declaration)?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- C++中的别名声明
- 应用于类型别名声明的 [[maybe_unused]] 属性的语法
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 替代班级内声明类型的别名
- 为什么我可以使用类型别名声明常量引用
- 如何使用别名声明模板化函数类型定义
- 将这些模板转换为别名声明
- 如何将所有别名、声明和初始化放在一起
- C++在不同的类中使用别名模板声明
- 我可以使用相同的名称为周围作用域中的类型声明成员类型别名吗
- 无法声明函数中的模板类型别名
- 在不键入别名类型的完整声明的情况下,无法从类模板定义中访问类型的类型别名
- 这是否仍然声明一种指针函数的别名?
- 如果模板别名声明可以解决新的类型家庭
- 解耦嵌套类:使用模板别名时出现"模板声明冲突"错误
- 在C++中,如何为std::array声明别名
- 如何在c++中转发声明别名模板