With template metaprogramming, the TD trick can be used to print the type of expressions as an error message at compile time.
This is really useful to debug templates. Is there a similar way to print values that are computed at compile-time?
Yes, and the code looks really similar: You declare (but not define) a template struct
that has the value as a template parameter. By trying to instantiate it without defining it, you get a compiler error that spells out the constant value:
template <int val>
struct PrintConst;
PrintConst<12*34> p;
When compiling this code, g++
fails with the following error:
const-display.cpp:4:19: error: aggregate ‘PrintConst<408> p’ has incomplete type and cannot be defined
PrintConst<12*34> p;
^
Note that it shows both the expression 12*34
, as well as the resulting value 408
.
You can use static_assert
for this job too:
template<int val>
void static_print()
{
static_assert(val & false, "");
}
int main()
{
static_print<12*34>();
}
which output on 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, "");
or in clang:
x.cc:9:2: note: in instantiation of function template specialization 'static_print<408>' requested here
static_print<12*34>();
^