Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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

  1. with #pragma and static_assert, I could not embed an integral(20 here) into a message;
  2. with preprocessors, it's too early that N is not substituted with 20 yet.

Is there any way or no way?

Thanks.

like image 640
t.g. Avatar asked Dec 01 '09 13:12

t.g.


People also ask

Are templates resolved at compile-time?

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!

How are CPP templates compiled?

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.

Can we pass Nontype parameters to templates?

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.

What is the rule of compiler by templates?

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.


1 Answers

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!

like image 195
Dan Moulding Avatar answered Oct 07 '22 12:10

Dan Moulding