Interesting problem related to Templates and typeid

Hi,

I encountered this interesting problem related to template and typeid. I am checking the typeid of the instantiated template and taking the action based on the class type of the instantiated template. Here is a small program I have written to demonstrate this.

template <class T>
class disp {

private:
T n;

public:

disp(T k) {
n=k;
}

void show(void) {
if (typeid(T) == typeid(int)) {
int k=n;
cout << "int=" << k << endl;
} else if (typeid(T) == typeid(string)) {
string s=n;
cout << "string=" << s << endl;
} else {
cout << "other non supported types" << endl;
}

}
};

int main (void) {

disp<int> d(10);
d.show();

return 0;
}

I am getting following compilation error:

testTemplate.cpp:30: instantiated from here
testTemplate.cpp:18: error: invalid conversion from ‘int’ to ‘const char*’
testTemplate.cpp:18: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’

I can understand this error which says I am trying to assign one datatype to another, but that will never happen as that code region will never be reached because there is a type checking before that in If clause.

How should I do these type of tasks if this is not the way to do this,
What I want to do is to have a generic class template, and based on data type of the instantiated template I want to perform certain operations that are permitted to some particular datatype. In this e.g it is just an assignment operation.

I will be thankful if you folks can throw some light on this issue, feel free to ask for clarification.

Thanks
It doesn't matter if the code won't be run for those types; it's compiled anyway, and thus generates the error. When you create a disp<int>, the compiler creates an class for disp replacing all the T's by int's and compiles them as such.

I think what you are doing is going against the point of templates. They are supposed to let you work with any type generically, not take any type and go back, figuring out what it was originally and doing things with it.
If you need to do something different (like an optimization) you could especialize the template.
1
2
3
4
template <>
void disp<int>::show(){
	cout << "int";
}

It is not verbose, but you could use typeid(T).name();
Thank you very much for your answers, Makes sense, wrong design, I think I should use template specialization
for this purpose.
Topic archived. No new replies allowed.