ein*_*ica 8 c++ g++ compile-time debug-print clang++
在这个问题中:
我们有一些关于如何让典型的 C++ 编译器在编译时打印类型名称的建议。但是,它们依赖于触发编译错误。
我的问题:我可以让 C++ 编译器在不停止编译的情况下打印类型的名称吗?
一般来说,答案是“可能不是”,因为一个有效的程序可以编译成它的目标对象,而无需在任何地方打印任何内容,所以我特别询问 GCC 和 clang,可能使用预处理器指令、编译器内置程序或任何编译器- 特定的技巧。
笔记:
using/typedef语句、模板参数值、可变参数模板等后面打印类型。如果类型明确可用,您可以使用类似的东西#message "my type is unsigned long long"(如@NutCracker 建议的那样)。但这不是问题的内容。以下机制由 @JonathanWakely 提供,并且特定于 GCC:
int i;
template <typename T>
[[gnu::warning("type printed for your convenience")]]
bool your_type_was_() { return true; }
#define print_type_of(_x) your_type_was_<decltype(_x)>()
bool b = print_type_of(i);
Run Code Online (Sandbox Code Playgroud)
这给你:
<source>: In function 'void __static_initialization_and_destruction_0(int, int)':
<source>:7:55: warning: call to 'your_type_was_<int>' declared with attribute warning: type printed for your convenience [-Wattribute-warning]
7 | #define print_type_of(_x) your_type_was_<decltype(_x)>()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
<source>:9:10: note: in expansion of macro 'print_type_of'
9 | bool b = print_type_of(i);
| ^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
看看它在 Godbolt 上的工作情况。
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |