如何使用typeid来确定指针中数据的类型

How to use typeid to to figure its type for the data in a pointer?

本文关键字:数据 类型 指针 定指 何使用 typeid      更新时间:2023-10-16

我有一个栈类的push item函数。我想检查*数据是否有空值,如果有返回异常。问题是我为字符串创建了堆栈类,后来更改了它,以便可以使用泛型类型。现在*data->data()不能用于除字符串以外的任何其他类型。所以我想检查每个*数据类型。所以我添加了一个If语句来检查指针Id是否像字符串。

因此,通过这样做,我希望if(*data->data()只对字符串执行。但问题是它也会检查整数。我一直得到这个错误:错误:成员引用基类型'int'不是一个结构或联合。如何解决这个问题?
      void push(Node<T> **head,T *data){

    string s = typeid(*data).name();
    if(s=="NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE"){
        if(*data->data() == NULL){
            throw NoDataException();
        }
    }
    else{
        if(s=="i"){
            cout<<"here"<<endl;
        }
    }
    Node<T> *temp = new Node<T>;
    temp->data = data;
    temp->next = *head;
    *head = temp;
};

使用辅助函数进行检查。

增加以下功能:

// A generic function for all types.
template <typename T> bool isEmpty(T const& t) { return false; }
// An overload for std::string.
bool isEmpty(std::string const& s) { return s.empty(); }

然后,替换为:

string s = typeid(*data).name();
if(s=="NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE") {
    if(*data->data() == NULL){
        throw NoDataException();
    }
}
else{
    if(s=="i"){
        cout<<"here"<<endl;
    }
}

if ( isEmpty(*data) ) {
   throw NoDataException();
} else {
   // ...
}