代码之家  ›  专栏  ›  技术社区  ›  anderas

如何在编译时打印常量值?

  •  0
  • anderas  · 技术社区  · 6 年前

    使用模板元编程, TD trick 可以用来打印 类型 在编译时作为错误消息的表达式。

    这对于调试模板非常有用。有类似的打印方法吗 价值观 是在编译时计算的?

    2 回复  |  直到 6 年前
        1
  •  3
  •   anderas    6 年前

    是的,代码看起来非常相似:您声明(但不定义)一个 template struct 将值作为模板参数的。通过尝试在不定义它的情况下实例化它,您将得到一个编译器错误,该错误指出常量值:

    template <int val>
    struct PrintConst;
    
    PrintConst<12*34> p;
    

    编译此代码时, g++ 失败,出现以下错误:

    const-display.cpp:4:19: error: aggregate ‘PrintConst<408> p’ has incomplete type and cannot be defined
     PrintConst<12*34> p;
                       ^
    

    注意,它同时显示了 12*34 ,以及结果值 408 .

        2
  •  3
  •   Amadeus    6 年前

    你可以使用 static_assert 对于这项工作:

    template<int val>
    void static_print()
    {
        static_assert(val & false, "");
    }
    
    int main()
    {
        static_print<12*34>();
    }
    

    在g++上的哪个输出:

    x.cc: In instantiation of ‘void static_print() [with int val = 408]’:
    x.cc:9:22:   required from here
    x.cc:4:20: error: static assertion failed
      static_assert(val & false, "");
    

    或在铿锵声中:

    x.cc:9:2: note: in instantiation of function template specialization 'static_print<408>' requested here
        static_print<12*34>();
        ^