如何在编译时打印恒定值?

时间:2018-12-21 15:30:48

标签: c++ templates template-meta-programming

通过模板元编程,TD trick可用于在编译时将表达式的类型打印为错误消息。

这对于调试模板非常有用。有没有类似的方法来打印在编译时计算出的 values

2 个答案:

答案 0 :(得分:3)

是的,代码看起来真的很相似:您声明(但未定义)具有该值作为模板参数的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

答案 1 :(得分:3)

您也可以使用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>();
    ^