gpt4 book ai didi

c++ - 在 C++ 中比较类型名称

转载 作者:可可西里 更新时间:2023-11-01 17:14:24 25 4
gpt4 key购买 nike

我将其输入到模板函数中,只是为了看看它是否有效:

if (T==int)

并且智能感知没有提示。这是有效的 C++ 吗?如果我这样做了怎么办:

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

最佳答案

为了满足您的要求,您应该使用 typeid 运算符。然后你的表情看起来像

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

说明这确实有效的明显示例:

#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;
}

所以在标准输出中你可能会得到:

0
1

关于c++ - 在 C++ 中比较类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3930379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com