Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiating alias and real-types at compile time?

Tags:

c++

alias

c++14

I have written a template function that takes arbitrary number of types and display their sizes for the underlying architecture and the operating system. However, the function is not able to differ an alias from a real-type so it is evaluated as if it is a real-type.

Yet I want to be able to differentiate an alias and built-in type at compile-time and alternate the output based on it.

func<unsigned int, size_t>();

Output:

Unsigned int is 4 bytes.
Unsigned int is 4 bytes. 

However, I want output to be like,

Unsigned int is 4 bytes.
size_t is an alias for unsigned int.

Of course that requires the compiler to be able to differentiate an alias and a built-in type at compile time.

So, is there way of differentiating a the real type and an alias at compile time in any C++ version?

like image 416
nmd_07 Avatar asked Jan 10 '17 17:01

nmd_07


2 Answers

The answer is that you can't do it now. However, there is a proposal for static reflection: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0194r2.html

In this document, they mention Operation get_base_name which will return the type name. However they state:

The get_base_name invoked on a meta::Alias returns the alias name, not the name of the aliased declaration.

They then provide Operation get_aliased, which can be used to obtain the original type of an alias when used with get_base_name.

The example code from the document:

 using rank_t = int;

 using mR = reflexpr(rank_t); 
 cout << "5:" << get_base_name_v<mR> << endl; 
 cout << "6:" << get_base_name_v<get_aliased_m<mR>> << endl;

produces the following output:

 5:rank_t; 
 6:int;

Bonus: If you have an interest in trying this now, the following document, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0385r1.pdf, mentions that there is an initial experimental implementation on a clang fork on GitHub here: https://github.com/matus-chochlik/clang/tree/reflexpr.

like image 99
Mikel F Avatar answered Nov 18 '22 09:11

Mikel F


You're out of luck.

There is, sadly, no way of distinguishing at compile-time or runtime if a type is a primitive type, or a typedef of a primitive type.

like image 5
Bathsheba Avatar answered Nov 18 '22 08:11

Bathsheba