开发者

Comparing typenames in C++

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

if (T==int)

and the intellisense didn't complain. Is this valid C++? What if I did:

std::cout << (int)int;  // looks stupid doesn't i开发者_StackOverflow社区t.


Just to fit your requirement you should use typeid operator. Then your expression would look like

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

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 in stdout you'll probably get:

0
1


No, this is not valid C++.

IntelliSense is not smart enough to find everything that is wrong with code; it would have to fully compile the code to do that, and compiling C++ is very slow (too slow to use for IntelliSense).


Is this what you're trying to do?

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

and this?

cout << typeid(int).name();


Your probably didn't even instantiate your template, that's why it compiled.


No, you can't use if (T == int) and std::cout<<(int)int;


Since C++11, you can use std::is_same<T1, T2>::value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜