Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c++ - Print template typename at compile time

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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). 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...