在编译时区分别名和真实类型?
Differentiating alias and real-types at compile time?
我编写了一个模板函数,它接受任意数量的类型并针对底层架构和操作系统显示它们的大小。但是,该函数无法区分别名和实型,因此它被评估为就好像它是实型一样。
但我希望能够在编译时区分别名和内置类型,并根据它交替输出。
func<unsigned int, size_t>();
输出:
Unsigned int is 4 bytes.
Unsigned int is 4 bytes.
但是,我希望输出像,
Unsigned int is 4 bytes.
size_t is an alias for unsigned int.
当然这要求编译器能够在编译时区分别名和内置类型。
那么,在任何 C++ 版本中,有没有办法在编译时区分真实类型和别名?
你运气不好。
遗憾的是,没有办法在编译时或运行时区分类型是原始类型还是原始类型的 typedef。
答案是你不能现在。不过有静态反射的提议:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0194r2.html
在本文档中,他们提到了 Operation get_base_name
这将 return 类型名称。然而他们说:
The get_base_name invoked on a meta::Alias returns the alias name, not
the name of the aliased declaration.
然后他们提供Operation get_aliased
,当与get_base_name
一起使用时,可用于获取别名的原始类型。
文档中的示例代码:
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;
奖励:如果您现在有兴趣尝试此操作,请阅读以下文档,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。
我编写了一个模板函数,它接受任意数量的类型并针对底层架构和操作系统显示它们的大小。但是,该函数无法区分别名和实型,因此它被评估为就好像它是实型一样。
但我希望能够在编译时区分别名和内置类型,并根据它交替输出。
func<unsigned int, size_t>();
输出:
Unsigned int is 4 bytes.
Unsigned int is 4 bytes.
但是,我希望输出像,
Unsigned int is 4 bytes.
size_t is an alias for unsigned int.
当然这要求编译器能够在编译时区分别名和内置类型。
那么,在任何 C++ 版本中,有没有办法在编译时区分真实类型和别名?
你运气不好。
遗憾的是,没有办法在编译时或运行时区分类型是原始类型还是原始类型的 typedef。
答案是你不能现在。不过有静态反射的提议:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0194r2.html
在本文档中,他们提到了 Operation get_base_name
这将 return 类型名称。然而他们说:
The get_base_name invoked on a meta::Alias returns the alias name, not the name of the aliased declaration.
然后他们提供Operation get_aliased
,当与get_base_name
一起使用时,可用于获取别名的原始类型。
文档中的示例代码:
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;
奖励:如果您现在有兴趣尝试此操作,请阅读以下文档,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。