How to print an integral template argument at compile time in C++

c++, templates

Solution

You could add a post-build step that finds all instantiations within the output binary after all compilations of the template(s) are complete. For instance, using the GNU toolchain you could do this:

make
nm foo | c++filt | grep 'C<[^>]\+>::f'

Where `foo` is the name of the output binary.

The regular expression obviously needs to be altered to find the template instantiations you are looking for, but this example works for your example `class C`.

You could even use a very broad regex to find all template instantiations, of any kind:

grep '<[^>]\+>::'

This is incidentally a great way to illustrate how use of the STL or iostream libraries bloats even seemingly tiny programs. The number of template instantiations can be truly astounding!

Problem

Say I have implemented a template class like this: ``` template <size_t N> class C { void f() { // print out N here? } }; ``` I wish that while the compiler compiles a clause like ``` C<20> c; ``` it would print out a message "class C is templated with N = 20" I've tried with #pragma and static_assert in vain. The problem is that - with #pragma and static_assert, I could not embed an integral(20 here) into a message; - with preprocessors, it's too early that N is not substituted with 20 yet. Is there any way or no way? Thanks.

Original source