Type Comparison in C ++

I typed this into a template function to see if this would work:

if (T==int) 

and intellisense did not complain. Is it really C ++? What if I did:

 std::cout << (int)int; // looks stupid doesn't it. 
+7
c ++
source share
5 answers

To meet your requirement, you must use the typeid operator. Then your expression will look like

 if (typeid(T) == typeid(int)) { ... } 

An obvious sample to illustrate that this really works:

 #include <typeinfo> #include <iostream> template <typename T> class AClass { public: static bool compare() { return (typeid(T) == typeid(int)); } }; void main() { std::cout << AClass<char>::compare() << std::endl; std::cout << AClass<int>::compare() << std::endl; } 

So you can, for example, get:

 0 1 
+7
source share

No, this is not valid C ++.

IntelliSense is not smart enough to find everything that is wrong with the code; it will have to completely compile the code for this, and C ++ compilation is very slow (too slow to use for IntelliSense).

+5
source share

No, you cannot use if (T == int) and std :: cout <(lt) int;

+1
source share

You may not even have created an instance of your template, so you compiled it.

+1
source share

Is this what you are trying to do?

 if(typeid(T) == typeid(int)) 

and this?

 cout << typeid(int).name(); 
+1
source share

All Articles