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
Is there any way or no way?
Thanks.
All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!
Template compilation requires the C++ compiler to do more than traditional UNIX compilers have done. The C++ compiler must generate object code for template instances on an as-needed basis. It might share template instances among separate compilations using a template repository.
Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
The compiler usually instantiates members of template classes independently of other members, so that the compiler instantiates only members that are used within the program. Methods written solely for use through a debugger will therefore not normally be instantiated.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With