-
Distinguishing types
Hi,
I was wondering if someone could help me.
I have a template function where based on the type passed in
I have to possibly access a struct member or just print the value.
Yet when I try to compile this it fails with tons of errors.
Code:
#include <typeinfo>
#include <iostream>
using namespace std;
typedef struct {
double a;
double b;
} A;
template<class E> void check_el(E val) {
if(typeid(E) == typeid(int)) {
cout << val << endl;
} else if(typeid(E) == typeid(A)){
double t = val.a;
cout << t << endl;
} else {
cout << "NOTHING" << endl;
}
}
int main() {
A a = {1, 2};
check_el<A>(a);
check_el<int>(5);
return 0;
}
How would I go about fixing this?
Thanks a lot for any help,
Tony
-
My guess is that you can't use templates with typeid, I might be wrong though. Simple remark, however, you don't need to use the typedef trick for structures in C++. It's a problem that's been fixed from C to C++.
-
Instead of trying to implement a function that determines the type of data passed in, you will have more success outputting the data as you normally would with cout.
To do so you will merely need to provide an ostream << operator overloading function for each structure that handles its output.
Then, whenever you do something like:
Code:
A val;
val.a = 10;
val.b = 15;
cout << val << endl;
It will automatically output the structure as you implemented it with the overloaded function.
-
Using templates with typeid is perfectly valid. The problem is that the ifs are runtime checks, not compile-time, so the entire function must compile properly with whatever type you put in. So even if T is int, the compiler expects the argument to have an 'a' member, and will throw an error if it doesn't.
-
Thanks a lot for the suggestions and pointers guys.