简体   繁体   English

比较C ++中的类型名称

[英]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. 并且intellisense没有抱怨。 Is this valid C++? 这是有效的C ++吗? What if I did: 如果我做了怎么办:

std::cout << (int)int;  // looks stupid doesn't it.

Just to fit your requirement you should use typeid operator. 只是为了满足您的要求,您应该使用typeid运算符。 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: 所以在stdout你可能会得到:

0
1

No, this is not valid C++. 不,这不是有效的C ++。

IntelliSense is not smart enough to find everything that is wrong with code; IntelliSense不够聪明,无法找到代码出错的一切; it would have to fully compile the code to do that, and compiling C++ is very slow (too slow to use for IntelliSense). 它必须完全编译代码才能做到这一点,并且编译C ++非常慢(用于IntelliSense的速度太慢)。

不,你不能使用if(T == int)和std :: cout <<(int)int;

您可能甚至没有实例化您的模板,这就是它编译的原因。

Is this what you're trying to do? 这是你想要做的吗?

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

and this? 还有这个?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM