Operator to tell the type

Is there any operator that I can act upon a variable and it will output its type?

Thanks.
1
2
3
4
5
#include <typeinfo>
....
....
....
cout << typeid(a).name() << endl;



where a is the variable.
Note that:

1. type_info::name() returns runtime type information

2. the value returned by type_info::name() doesn't have to be a pretty name.

Output when compiled with GCC (MinGW):
type of int is i
type of i is i
type of a is A2_A3_i
type of EmptyClass is 10EmptyClass
type of c is 10EmptyClass
type of dump<int, 8> is FvRA8_iE


Aside: If you want/need to 'unmangle' the name returned by GCC's implementation of type_info, see here:
http://www.cplusplus.com/forum/beginner/166020/#msg836699

Output when compiled with MSVC:
type of int is int
type of i is int
type of a is int [2][3]
type of EmptyClass is class EmptyClass
type of c is class EmptyClass
type of dump<int, 8> is void __cdecl(int (&)[8])


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <typeinfo>

class EmptyClass {
    // empty, boring class
};

inline double sqr(double x) {
    return (x * x);
}

template<typename TElem, int NElems>
void dump(TElem (&a)[NElems]) {
    for(int i = 0; NElems > i; ++i) {
        std::cout << " " << a[i];
    }
}

#define REPORT_TYPE(V) \
    std::cout << "type of " #V " is " << typeid(V).name() << "\n"

int main() {
    int i = 0;
    int a[2][3] = {0};
    EmptyClass c = EmptyClass();

    REPORT_TYPE(int);
    REPORT_TYPE(i);
    REPORT_TYPE(a);
    REPORT_TYPE(EmptyClass);
    REPORT_TYPE(c);
    // template itself does not have an actual type -- just its instantiations
    // too lazy to concoct macro solution for this:
    std::cout << "type of dump<int, 8> is " << typeid(dump<int, 8>).name() << "\n";

    return 0;
}


Andy
Last edited on
thanks.
Topic archived. No new replies allowed.