【发布时间】:2018-12-21 15:30:48
【问题描述】:
使用模板元编程,TD trick 可用于在编译时将表达式的类型打印为错误消息。
这对于调试模板非常有用。是否有类似的方法来打印在编译时计算的 值?
【问题讨论】:
标签: c++ templates template-meta-programming
使用模板元编程,TD trick 可用于在编译时将表达式的类型打印为错误消息。
这对于调试模板非常有用。是否有类似的方法来打印在编译时计算的 值?
【问题讨论】:
标签: c++ templates template-meta-programming
是的,代码看起来非常相似:您声明(但未定义)一个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。
【讨论】:
您也可以使用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>();
^
【讨论】: