微信公众号:OpenCV学堂
关注获取更多计算机视觉与深度学习知识
前言
使用typeid.name()方法
使用std::is_same方法
代码实现与运行效果如下:
使用dynamic_cast
1#include
2#include
3#include
4
5using namespace cv;
6using namespace std;
7
8class Vehicles {
9public:
10 string make;
11 string model;
12 string year;
13};
14
15class Aircraft {
16public:
17 string make;
18 string model;
19 string year;
20};
21
22template <typename T>
23void printType() {
24 if (std::is_same::value) {
25 std::cout << "Type is Aircraft" << std::endl;
26 }
27 else if (std::is_same::value) {
28 std::cout << "Type is Vehicles" << std::endl;
29 }
30 else {
31 std::cout << "Type is unknown" << std::endl;
32 }
33}
34
35class Base {
36public:
37 virtual ~Base() {} // Adding a virtual destructor for polymorphism
38};
39class Derived : public Base {
40 // Class definition
41};
42int main(int argc, char** argv) {
43 Base baseObj;
44 Derived derivedObj;
45 Base* ptrBase = &derivedObj;
46 Derived* ptrDerived = dynamic_cast(ptrBase);
47 if (ptrDerived) {
48 std::cout << "Object is of type Derived" << std::endl;
49 }
50 else {
51 std::cout << "Object is not of type Derived" << std::endl;
52 }
53
54
55
56 Vehicles car;
57 Aircraft craft;
58 const char* name1 = typeid(car).name();
59 const char* name2 = typeid(craft).name();
60 std::cout << "object name: " << name1 << std::endl;
61 std::cout << "object name: " << name2 << std::endl;
62
63 printType();
64 printType();
65
66 return 0;
67}
推荐阅读
ZXING+OpenCV打造开源条码检测应用
攻略 | 学习深度学习只需要三个月的好方法
三行代码实现 TensorRT8.6 C++ 深度学习模型部署
实战 | YOLOv8+OpenCV 实现DM码定位检测与解析
对象检测边界框损失 – 从IOU到ProbIOU
初学者必看 | 学习深度学习的五个误区