Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print template typename at compile time

Tags:

c++

g++

When creating a template function in C++ is there a simple way to have the typename of the template represented as a string? I have a simple test case to show what I'm trying to do (note the code shown does not compile):

#include <stdio.h> template <typename type> type print(type *addr)  {   printf("type is: %s",type); }  int main() {   int a;   print(&a); }  // Would like to print something like: // type is: int 

I think that the typename should be available at compile time when the function is instantiated, but I'm not that familiar with templates and I haven't seen a way to get the typename as a string.

The reason that I want to do this is for some printf type debugging. I have multiple threads running and stepping through with gdb changes the program behavior. So for some things I want to dump information about which functions were executing. It's not too important so if the solution is overly complex I would skip adding this information to my logging function. But if there was a simple way to do this it would be useful information to have.

like image 891
Gabriel Southern Avatar asked Mar 21 '12 21:03

Gabriel Southern


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!

What is Typename in template?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

Which keyword is equivalent to Typename in C++ template?

For naming template parameters, typename and class are equivalent.


1 Answers

To get a useful compile time name:

Supposing you have some unknown type named 'T'. You can get the compiler to print it's type by using it horribly. For example:

typedef typename T::something_made_up X; 

The error message will be like:

error: no type named 'something_made_up' in 'Wt::Dbo::ptr<trader::model::Candle>' 

The bit after 'in' shows the type. (Only tested with clang).

Other ways of triggering it:

bool x = T::nothing;   // error: no member named 'nothing' in 'Wt::Dbo::ptr<trader::model::Candle>' using X = typename T::nothing;  // error: no type named 'nothing' in 'Wt::Dbo::ptr<trader::model::Candle>' 

With C++11, you may already have an object and use 'decltype' to get its type, so you can also run:

auto obj = creatSomeObject(); bool x = decltype(obj)::nothing; // (Where nothing is not a real member).  
like image 167
matiu Avatar answered Sep 20 '22 13:09

matiu