Jia Rui Jia Rui - 1 month ago 11
C++ Question

using type alias such as using A = int(int)

With type alias we could introduce new type alias for example

using A = int(*)(int);


is similar to

typedef int(*A)(int);


I find the following code is also legal for current C++ compiler

using A = int(int);


I was wondering what's the type of A and how to use it ( I did not find it useful myself)

Here's the code, it works in gcc 6.3 and clang 4.0

#include <iostream>
#include <functional>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
using A = int(int);
using B = int(*)(int);

int main(){
int status;
cout<<sizeof(A)<<endl; //Error in clang 4.0
cout<<sizeof(B)<<endl;
cout<<sizeof(function<int(int)>)<<endl;
cout<<typeid(A).name()<<endl;
cout<<typeid(B).name()<<endl;
cout<<typeid(function<int(int)>).name()<<endl;
cout<<abi::__cxa_demangle(typeid(A).name(), 0, 0, &status)<<endl;
cout<<abi::__cxa_demangle(typeid(B).name(), 0, 0, &status)<<endl;
cout<<abi::__cxa_demangle(typeid(function<int(int)>).name(), 0, 0, &status)<<endl;
return 0;
}


The output is

1
4
16
FiiE
PFiiE
St8functionIFiiEE
int (int)
int (*)(int)
std::function<int (int)>

Answer Source

A is int(int) as stated.

It's a function type, not an object type, so you cannot declare an object of type A or appy sizeof to it (gcc gives you a warning about it). You however can use A* which is a normal function pointer type:

A* a = myfunc;

You can also use A to instantiate a template, e.g std::function<A>.