What do you think of my footwork?

A while ago I remember asking on here something about trying to do something like this. (To be able to get the type of a variable). And I was told it wasn't possible. (Or it was tricky. I don't remember exactly. )

Well look like its pretty simple after all.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
enum KIND { INT = 1, BOOL, FLOAT, DOUBLE, CHAR, STRING, CHARPOINTER };

template <class it> int get_type(const it & other) {  return -1;}
int get_type(const string & s) { return STRING;}
int get_type(const char & c) { return CHAR; }
int get_type(const double & d) {return DOUBLE; }
int get_type(const float & f) { return FLOAT; }
int get_type(const bool & b) { return BOOL; }
int get_type(const int & i) { return INT; }
int get_type(const char * & cp) { return CHARPOINTER;}
int get_type(char * cp) { return CHARPOINTER; }

template <class it>
void couttype(const it & item)
{
    switch (get_type(item))
        {
            case INT:
                cout << "That is an int. \n" << endl;
                break;

            case BOOL:
                cout << "That is a bool. \n" << endl;
                break;

            case CHAR:
                cout << "That is a char. \n" << endl;
                break;

            case FLOAT:
                cout << "That is a float.\n" << endl;
                break;

            case DOUBLE:
                cout << "That is a double. \n" << endl;
                break;

            case STRING:
                cout << "That is a string. \n" << endl;
                break;

            case CHARPOINTER:
                cout << "That is a char pointer. \n" << endl;
                break;

            default:
                cout << "That is something other. \n" << endl;
                break;
        }
    return;
}

int main()
{
     int i; char c; bool b; double d; float f; char * cp; string s; 
     couttype(b);
     return 0;
}

see?
You should look into typeid..
Topic archived. No new replies allowed.