V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
LitostCheng
V2EX  ›  C++

关于 C++中 type_name 关键字的理解与应用

  •  
  •   LitostCheng · 2019-09-24 15:03:16 +08:00 · 3132 次点击
    这是一个创建于 1669 天前的主题,其中的信息可能已经有所发展或是发生改变。

    关于 C++中 type_name 关键字的理解与应用

      今天在 Github 上有看到一个有趣的项目:dbg-macro。见名知意:其功能类似于一个 Debug 宏,但比较有趣的地方在于,其能够输出变成语句,以及相应的结果,而不需要我们通过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__))
    

    代码连接点这里

      还往各位大神试点迷津。

    3 条回复    2019-09-24 19:47:37 +08:00
    hardwork
        1
    hardwork  
       2019-09-24 16:20:31 +08:00
    type_name 不是关键字,只是一个模板函数,返回值是 std::string, 你在代码里搜这个函数就看到了
    GeruzoniAnsasu
        2
    GeruzoniAnsasu  
       2019-09-24 16:25:15 +08:00   ❤️ 1
    LitostCheng
        3
    LitostCheng  
    OP
       2019-09-24 19:47:37 +08:00
    @GeruzoniAnsasu 嗯嗯,我再好好看看,
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2594 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:43 · PVG 09:43 · LAX 18:43 · JFK 21:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.