我正在尝试创建一个使用模板和向量的标题,这些标题将根据数据的内容以数字或字母顺序按升序对数组进行排序。但是,我需要在组织之前检查类型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++)
{
}
}
答案 0 :(得分:0)
您想在此处使用功能专长:
template<typename T>
class SortableVector {
private:
T* _internal;
/* ... */
public:
void sort();
};
template<typename T>
void SortableVector<T>::sort() {
/* sort a general unknown type */
}
template<>
void SortableVector<bool>::sort() {
/* sort bools */
}
template<>
void SortableVector<int>::sort() {
/* sort ints */
}
/* etc. */