How to output C ++ type information at compile time

all. I am debugging some type mismatch problem of a strongly templated class. I would like to know C ++ type information at compile time, so I write this:

#pragma message typeinfo(var)

      

It just doesn't work.

So, I'm here asking for help. I'm not sure if this is possible. But I think the compiler needs to know the type information at compile time.

+3


source to share


2 answers


The preprocessor won't help you at compile time. This job is preprocessing that happens before compilation.

If the idea is to output the type information at compile time try this

template <typename...> struct WhichType;
class Something {};

int main() {
    WhichType<Something>{};
}

      

Here's a live example . When you compile this, you should get an error that gives you the type of what is inside the templates when you try to instantiate WhichType

. It was a neat trick I took from Scott Meyers' book Modern Modern C ++. It seems to work fine with most of the compilers that I have come across so far.



If you want to get type information at runtime

#include <iostream>
#include <typeinfo>

using std::cout;
using std::endl;

int main() {
    auto integer = int{};
    cout << typeid(integer).name() << endl;
}

      


Note Not too comfortable with RTTI (RunTime information) via typeid

, C ++ also offers several compile-time type introspection utilities http://en.cppreference.com/w/cpp/header/type_traits .

+6


source


I am using a printer type helper function that simply builds on a predefined gcc macro __PRETTY_FUNCTION__

. Just write a templated function that eats forever and will call it where you need to know what type your template will expand to. It was very helpful for me to use such a function in case of SFINAE and others problems.

template <typename ... T>
void TemplatePrint(T ... args )
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main()
{
    auto any = std::tuple_cat( std::tuple<int, double>{}, std::tuple<std::string>{} );
    TemplatePrint( any );
}

      



You haven't tagged your question to a specific compiler, so you may need to look for equivalents for other compilers.

In C ++ con a year ago, it was about: https://baptiste-wicht.com/posts/2016/02/use-templight-and-templar-to-debug-cpp-templates.html . Perhaps this will help solve problems with the given templates.

+1


source







All Articles