【发布时间】:2020-11-17 22:04:55
【问题描述】:
有没有办法比较 C++ 中的变量类型?例如,我想要这样的东西:(使用伪语言)
template <class T> void checkType(T variable) {
if(type_of(T) == int) cout << "The variable is of type int.\n";
}
编辑 1:我尝试使用 is_same,但它在 Xcode 中不起作用...但是当我尝试在 Atom 中使用 Script 包的以下简单代码中使用它时,它会运行。
#include <iostream>
using namespace std;
template <class T> void print(T value) {
if(is_same<T, char> :: value) cout << "char\n";
if(is_same<T, int> :: value) cout << "int\n";
if(is_same<T, string> :: value) cout << "string\n";
}
int main() {
string var1;
int var2;
char var3;
print(var1);
print(var2);
print(var3);
return 0;
}
编辑 2:我将不起作用的代码放在这里。现在我尝试评论有关字符串的部分,代码适用于 int 和 char。
template <class keytype, class attrtype>
void LinkedList <keytype, attrtype> :: insert(keytype k, attrtype a) {
LinkedList <keytype, attrtype> :: position iter = l.head();
if(is_same<keytype, int> :: value) {
while(iter != NULL and k > iter -> key) {
iter = l.next(iter);
}
l.insert(iter, k, a);
}
else if(is_same<keytype, char> :: value) {
while(iter != NULL and tolower(k) > tolower(iter -> key)) {
iter = l.next(iter);
}
l.insert(iter, k, a);
}
//Whatever type I pass by the template in 'keytype' enters this if statement
else if(is_same<keytype, string> :: value) {
bool node_filled = false;
if(iter == NULL) {
l.insert(iter, k, a);
node_filled = true;
}
else {
unsigned long rif = 0;
int i = 0;
while(!node_filled and iter != NULL) {
if(tolower(iter -> key.at(0)) > tolower(k.at(0))) {
l.insert(iter, k, a);
node_filled = true;
}
else if(tolower(iter -> key.at(0)) < tolower(k.at(0))) {
iter = l.next(iter);
}
else if(tolower(iter -> key.at(0)) == tolower(k.at(0))) {
if(k.size() > iter -> key.size())
rif = iter -> key.size();
else
rif = k.size();
while((i < rif - 1) and (k.at(i) == iter -> key.at(i))) {
i ++;
}
if(tolower(iter -> key.at(i)) > tolower(k.at(i))) {
l.insert(iter, k, a);
node_filled = true;
}
else if(tolower(iter -> key.at(i)) == tolower(k.at(i))) {
if(k.size() < iter -> key.size()) {
l.insert(iter, k, a);
node_filled = true;
}
else {
iter = l.next(iter);
}
}
else if(tolower(iter -> key.at(i)) < tolower(k.at(i))) {
iter = l.next(iter);
}
}
}
if(!node_filled) {
l.insert(NULL, k, a);
}
}
}
}
【问题讨论】:
-
std::is_same<T, int>::value? -
Algirdas 是对的,而且更进一步 - 如果你想在
if语句中做一些只会为测试的特定类型编译的事情,你可以做类似if constexpr (std::is_same_v<T, int>) std::cout << "I can can add 2 to " << variable << " to get " << variable + 2 << std::endl;的事情 - 那不会如果T是std::string,则不会出现编译器错误。 (is_same_v助手让您不必附加::value)。 -
std::is_same<T, int>::value会为这个确切的问题提供一个很好的布尔值,但在实践中并不是特别常见,因为还有很多其他事情可以与其他事情一起进行类型比较,并选择正确的工具需要背景和对更广泛问题的看法。那么……你真正要解决的是什么? -
我有一个自己制作的LinkedList类,我想根据模板传递的List类型做一个排序算法。
-
错误是什么?
标签: c++ variables typeof typeid