1

How can I print a type list ??

here is what I tried + my type list :

template<typename ...T>
struct typeList;
template<typename H, typename ...T>
struct typeList<H, T...> {
    using head = H;
    using tail = typeList<T...>;
public:
    static inline void print(){
        std::cout << H::name << " "; // How can I get the name of H ???
        typeList<T...>::print();
    }
};

template<>
struct typeList<>{
   static inline void print(){
       std::cout << endl;
   }
};

so that typeList<A,B,C,int>::print() would give A b C int ,

A B and C are some user defined structs

Can I do this without adding a static function called name in every struct?? There is no compile time function that returns the type name ?

EDIT :

This is not a duplicate of this, where did I mention variables ??

7
  • Is en.cppreference.com/w/cpp/language/typeid insufficient? Commented Jun 15, 2015 at 10:13
  • @CaptainGiraffe A type_info object is not required to give you a useful name. Commented Jun 15, 2015 at 10:16
  • I've closed this question as a duplicate, because the main question appears to be about printing the name of a type. If that's the case, this might also help. Commented Jun 15, 2015 at 10:18
  • @Jefffrey anyway, my question is not a duplicate of stackoverflow.com/questions/81870/print-variable-type-in-c Commented Jun 15, 2015 at 11:59
  • 1
    @OthmanBenchekroun I know, but that question have this answer, which deals with how to print the type after you get it from the variable, which is indeed a duplicate of what you are asking here. Also have you tried reading the other question I linked? Commented Jun 15, 2015 at 12:10

1 Answer 1

2

You can use typeid(H).name() for this. Unfortunately, format of name() is implementation defined, so you can't rely on getting the output you expect in all cases.

For example, in GCC 4.9.2, typeList<A,B,C,int>::print() prints:

1A 1B 1C i

A possible solution would be to define a getTypeName template function which you specialize for the different types, then fall back on typeid().name() when you don't have a specialization:

template <typename T>
std::string getTypeName()
{
    return typeid(T).name();
}

template <>
std::string getTypeName<int>()
{
    return "int";
}

template <>
std::string getTypeName<A>()
{
    return "A";
}

This would print out:

A 1B 1C int

Then you could easily add specializations for your other types.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.