要比较由std::unique_ptr所指向的底层(派生)类型,可以使用typeid运算符来获取类型信息,并进行比较。以下是一个示例代码:
#include
#include
#include
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
void foo() {
std::cout << "Derived::foo()" << std::endl;
}
};
int main() {
std::unique_ptr ptr1 = std::make_unique();
std::unique_ptr ptr2 = std::make_unique();
if (typeid(*ptr1) == typeid(*ptr2)) {
std::cout << "ptr1 and ptr2 point to the same derived type." << std::endl;
} else {
std::cout << "ptr1 and ptr2 point to different derived types." << std::endl;
}
return 0;
}
在这个示例中,我们创建了两个std::unique_ptr,它们都指向Derived类型的对象。通过使用typeid运算符,我们可以比较ptr1和ptr2所指向的对象的类型。如果它们指向相同的派生类型,则输出"ptr1 and ptr2 point to the same derived type.",否则输出"ptr1 and ptr2 point to different derived types."。
请注意,这种方法只能用于比较两个特定的std::unique_ptr指针所指向的对象的类型,不能用于比较派生类型之间的继承关系。
上一篇:比较由PDF页面生成的TIF文件