Josh
Josh

Reputation: 1

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? is it a function? How can it be used?

Upvotes: 0

Views: 310

Answers (3)

Coral Kashri
Coral Kashri

Reputation: 3506

Just to give another use option of this line, with lambda expressions:

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.

This way came all the way from pure C programming, with the using twist. I won't recommend of choosing this way, but for general understanding it is always good to know more than the correct ways.

Upvotes: 0

Peter
Peter

Reputation: 36597

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

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

int(int a, int b) is a function declaration that has two parameters of the type int and the return type also int.

You can use this alias declaration for example as a member function declarations of a class or using it in a parameter declaration.

Upvotes: 1

Related Questions