【发布时间】:2014-05-06 17:57:46
【问题描述】:
我正在尝试创建一个使用模板和向量的标题,这些模板和向量将根据数组的内容按数字或字母顺序对数组进行升序排序。但是,我需要在组织它之前检查类型 o 变量,因为数组可以是 int 数组或字符串数组等。我知道如何组织它,但是如何检查变量类型以确定将其分配给哪个临时变量?这是我所拥有的:
template <class T>
void SortableVector<T>::sort()
{
int temp1 = 0;
double temp2 = 0;
float temp3 = 0;
string temp4 = "";
if (this->operator[](0) //is an int
{
temp1 = this->operator[](0);
}
else if (this->operator[](0) //is a double
{
temp2 = this->operator[](0);
}
else if( this->operator[](0) //is a float
{
temp3 = this->operator[](0);
}
else if (this->operator[](0) //is a string
{
temp4 = this->operator[](0);
}
for (int count = 0; count < this->size(); count++)
{
}
}
【问题讨论】:
-
T不是你的类型吗?你可以专门化你的功能。 -
编写模板的全部目的是让您不需要知道确切的类型。如果 T 是 int 与 string,你会写什么不同?
标签: c++ templates variables vector