Print template typename at compile time

后端 未结 6 1176
予麋鹿
予麋鹿 2020-12-08 09:41

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 try

6条回答
  •  星月不相逢
    2020-12-08 10:05

    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'
    

    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'
    using X = typename T::nothing;  // error: no type named 'nothing' in 'Wt::Dbo::ptr'
    

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

提交回复
热议问题