比较 If 语句中的数据类型
Comparing A Data Type in an If Statement
有没有办法在 if 语句中测试参数的数据类型?这是一个源代码的例子:它不会编译,但它用来表达我的意图。
typedef char cInt[sizeof(int)];
typedef char cFloat[sizeof(float)];
typedef char cDouble[sizeof(double)];
template<typename T>
char* convertToCharStr( const T& t ) {
if ( t == int ) {
cInt c = t;
return c;
}
if ( t == float ) {
cFloat c = t;
return c;
}
if ( t == double ) {
cDouble c = t;
return c;
}
return nullptr;
}
如您所见,我正在尝试创建一个模板函数,它可以采用任何默认数据类型,例如 int、unsigned int、float、double 和 depending
在数据类型上,它将根据传入的数据类型在堆栈上创建适当的char[]变量,并将数据存储到char[]和return函数外的指针。
我将保持原样,但请注意,字符数组应该是 unsigned char。
好吧,有一些使用 typeid
的方法,就像这里 Using typeid to check for template type 所做的那样,但我建议改用模板专业化,如下所示:
template<typename T>
char* convertToCharStr( const T& t ) {
//Maybe you might feel it more appropriate to put a static assert here
return nullptr;
}
template<>
char* convertToCharStr( const int& t ) {
cInt c = t;
return c;
}
template<>
char* convertToCharStr( const float& t ) {
cFloat c = t;
return c;
}
template<>
char* convertToCharStr( const double& t ) {
cDouble c = t;
return c;
}
见CPP Reference and this question for more of a discusion on it (and what else you can do..to avoid the pains of specialized templating). C++ templates specialization syntax
也就是说,在堆栈上创建一个变量然后 return 指向它的指针是不安全的,因为该变量将在函数调用的 return 上被取消堆栈并且很可能是稍后覆盖。
有没有办法在 if 语句中测试参数的数据类型?这是一个源代码的例子:它不会编译,但它用来表达我的意图。
typedef char cInt[sizeof(int)];
typedef char cFloat[sizeof(float)];
typedef char cDouble[sizeof(double)];
template<typename T>
char* convertToCharStr( const T& t ) {
if ( t == int ) {
cInt c = t;
return c;
}
if ( t == float ) {
cFloat c = t;
return c;
}
if ( t == double ) {
cDouble c = t;
return c;
}
return nullptr;
}
如您所见,我正在尝试创建一个模板函数,它可以采用任何默认数据类型,例如 int、unsigned int、float、double 和 depending 在数据类型上,它将根据传入的数据类型在堆栈上创建适当的char[]变量,并将数据存储到char[]和return函数外的指针。
我将保持原样,但请注意,字符数组应该是 unsigned char。
好吧,有一些使用 typeid
的方法,就像这里 Using typeid to check for template type 所做的那样,但我建议改用模板专业化,如下所示:
template<typename T>
char* convertToCharStr( const T& t ) {
//Maybe you might feel it more appropriate to put a static assert here
return nullptr;
}
template<>
char* convertToCharStr( const int& t ) {
cInt c = t;
return c;
}
template<>
char* convertToCharStr( const float& t ) {
cFloat c = t;
return c;
}
template<>
char* convertToCharStr( const double& t ) {
cDouble c = t;
return c;
}
见CPP Reference and this question for more of a discusion on it (and what else you can do..to avoid the pains of specialized templating). C++ templates specialization syntax
也就是说,在堆栈上创建一个变量然后 return 指向它的指针是不安全的,因为该变量将在函数调用的 return 上被取消堆栈并且很可能是稍后覆盖。