
今天在 Github 上有看到一个有趣的项目:dbg-macro。见名知意:其功能类似于一个 Debg 宏,但比较有趣的地方在于,其能够输出变成语句,以及相应的结果,而不需要我们通过printf等形式输出具体信息。 以下是一个具体的例子:
#include <vector> #include <dbg.h> // You can use "dbg(..)" in expressions: int factorial(int n) { if (dbg(n <= 1)) { return dbg(1); } else { return dbg(n * factorial(n - 1)); } } int main() { std::string message = "hello"; dbg(message); // [example.cpp:15 (main)] message = "hello" (std::string) const int a = 2; const int b = dbg(3 * a) + 1; // [example.cpp:18 (main)] 3 * a = 6 (int) std::vector<int> numbers{b, 13, 42}; dbg(numbers); // [example.cpp:21 (main)] numbers = {7, 13, 42} (size: 3) (std::vector<int>) dbg("this line is executed"); // [example.cpp:23 (main)] this line is executed factorial(4); return 0; } 本人在查看源码的过程中,对于以下实现中的dbg_macro::type_name不太理解:
#define dbg(...) \ dbg_macro::DebugOutput(__FILE__, __LINE__, __func__, #__VA_ARGS__) \ .print(dbg_macro::type_name<decltype(__VA_ARGS__)>(), (__VA_ARGS__)) 还往各位大神试点迷津。
1 hardwork 2019-09-24 16:20:31 +08:00 type_name 不是关键字,只是一个模板函数,返回值是 std::string, 你在代码里搜这个函数就看到了 |
2 GeruzoniAnsasu 2019-09-24 16:25:15 +08:00 https://github.com/sharkdp/dbg-macro/blob/f30cdda9fc5332e06201d886c9e6ec4b8f0f1216/dbg.h#L114 作用就是用 type trait 选择出类型,拼上字符串 |
3 LitostCheng OP @GeruzoniAnsasu 嗯嗯,我再好好看看, |