简体   繁体   English

C ++中的别名声明

[英]Alias Declarations in C++

I have come across this code snippet and have no idea what it means: 我遇到了这个代码片段,不知道这意味着什么:

#include <iostream>

int main(){
 using test = int(int a, int b); 

 return 0;
}

I can guess test can be used instead of int(int a, int b) , but what does int(int a, int b) even mean? 我猜想可以用test代替int(int a, int b) ,但是int(int a, int b)到底是什么意思? is it a function? 是功能吗? How can it be used? 如何使用?

int(int a, int b) is a function declaration that has two parameters of the type int and the return type also int . int(int a, int b)是一个函数声明,具有两个类型为int且返回类型也为int

You can use this alias declaration for example as a member function declarations of a class or using it in a parameter declaration. 您可以将此别名声明用作例如类的成员函数声明,或在参数声明中使用它。

It's an alias for a function signature. 它是函数签名的别名。

A more complete usage is to declare a pointer or reference to a function 更完整的用法是声明函数的指针或引用

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);
}

Just to give another use option of this line, with lambda expressions: 只是为了给该行提供另一个使用选项,带有lambda表达式:

int main() {
    using test = int(int, int);
    test le = [](int a, int b) -> int {
        return a + b;
    }
    return 0;
}

One point that you have to keep in mind about this use of test, there are probably more efficient ways to declare a function signature, like auto in lambda expressions case, template in case of passing function as argument to another function, etc. 关于测试的使用,您必须记住一点,可能有更有效的方法来声明函数签名,例如在lambda表达式中使用auto ,在将函数作为参数传递给另一个函数的情况下使用template ,等等。

This way came all the way from pure C programming, with the using twist. 这种方式完全来自纯C编程,并带有using I won't recommend of choosing this way, but for general understanding it is always good to know more than the correct ways. 我不建议您选择这种方式,但是对于一般的理解,了解更多的知识总是比正确的方法更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM