How do I check if a variable is of a given type?

I want to put a function into my program that outputs to the console the type of any given variable. The problem is that the outputted names of some - or all - types is implementation-defined, making typeid().name useless. Thus, I need to first check to see if the variable is of a given type. If the variable is an integer, for example, the program should print "integer".
Look at <type_traits>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <type_traits>
#include <iostream>

template <typename T>
void print_type() {
    if (std::is_integral<T>::value)
        std::cout << "integer\n";
    // ...
}

template <typename T>
inline void print_type(const T&) {
    print_type<T>();
}

int main() {
    int x;
    print_type(x); // integer
    print_type<int>(); // integer
    return 0;
}

If that isn't what you're looking for, the only other thing I can think of is to use std::type_index and std::unordered_map to create your own lookup table of type names. See http://www.cplusplus.com/reference/typeindex/type_index/ for an example.
Last edited on
Topic archived. No new replies allowed.