Skip to content

Commit 29a84e2

Browse files
committed
type erasure added
1 parent e4f419d commit 29a84e2

File tree

1 file changed

+111
-1
lines changed

1 file changed

+111
-1
lines changed

docs/type_erasure.md

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,112 @@
1+
# Type erasure
2+
3+
Type erasure in C++ is a technique used to abstract away the specific type of an object while still allowing operations on that object to be performed in a type-safe manner. This is particularly useful in situations where you want to work with objects of different types in a uniform way without losing the benefits of strong typing.
4+
5+
In C++, type erasure often involves creating a base class with virtual functions and derived classes that implement these functions for specific types. The base class acts as a common interface, while the derived classes handle the type-specific logic. Here's a simple example to illustrate this:
6+
7+
### Base Interface
8+
9+
First, you define a base class that provides a generic interface:
10+
11+
```cpp
12+
class AnyType {
13+
public:
14+
virtual ~AnyType() {}
15+
// Virtual methods that can be implemented by derived classes
16+
};
17+
```
18+
19+
### Derived Class
20+
21+
Next, create a template-derived class that can hold any type:
22+
23+
```cpp
24+
template<typename T>
25+
class Holder : public AnyType {
26+
T value;
27+
public:
28+
Holder(T v) : value(v) {}
29+
// Methods to interact with the value
30+
T getValue() const { return value; }
31+
void setValue(T v) { value = v; }
32+
};
33+
```
34+
35+
### Using Type Erasure
36+
37+
You can then create instances of `Holder` for different types and store them in a container that holds base class pointers:
38+
39+
```cpp
40+
#include <memory>
41+
#include <vector>
42+
43+
int main() {
44+
std::vector<std::unique_ptr<AnyType>> objects;
45+
46+
objects.push_back(std::make_unique<Holder<int>>(10));
47+
objects.push_back(std::make_unique<Holder<double>>(3.14));
48+
objects.push_back(std::make_unique<Holder<std::string>>("Hello, World!"));
49+
50+
// You can iterate over these objects and use them
51+
// but you've lost the specific type information.
52+
}
53+
```
54+
55+
### Limitations and Considerations
56+
57+
- The type-specific operations need to be known and defined in the base interface, which can limit flexibility.
58+
- Casting or dynamic type checking might be necessary to retrieve the original type, which can introduce runtime overhead.
59+
- This approach doesn't preserve type information, which can be a limitation in some scenarios.
60+
61+
Type erasure is a powerful tool in C++, especially in library design where you need to handle different types uniformly without exposing implementation details. However, it should be used judiciously as it comes with its own complexities and trade-offs.
62+
63+
# OpenCV Example
64+
65+
OpenCV, a popular library for computer vision, utilizes the concept of type erasure in several ways to handle a wide range of image types and matrix operations efficiently. One of the most notable implementations of type erasure in OpenCV is through the `cv::Mat` class, which is used for storing images and matrices.
66+
67+
### The `cv::Mat` Class
68+
69+
The `cv::Mat` class is a part of OpenCV's core module and is a good example of type erasure. It can store an image or a matrix of various data types (like `uint8`, `int`, `float`, etc.) and sizes, but the specific type information is not part of the `cv::Mat` type itself. Instead, the type information is stored internally and can be accessed at runtime.
70+
71+
Here's how type erasure is achieved in `cv::Mat`:
72+
73+
1. **Generalized Data Storage**: `cv::Mat` holds its data in a generic way, typically as a pointer to a memory block. The actual data type (e.g., `uint8`, `float`) is not part of the `cv::Mat` class's type.
74+
75+
2. **Runtime Type Information**: The data type and the number of channels in the matrix are stored as part of the `cv::Mat` object, typically in an integer format. This information is used at runtime to interpret the raw data correctly.
76+
77+
3. **Type-Safe Access**: OpenCV provides templated functions for accessing and manipulating `cv::Mat` data in a type-safe manner. These functions use the runtime type information to ensure that operations are performed correctly according to the actual data type.
78+
79+
### Example: Using `cv::Mat`
80+
81+
Here’s a basic example of how `cv::Mat` is typically used:
82+
83+
```cpp
84+
#include <opencv2/opencv.hpp>
85+
86+
int main() {
87+
// Create a 3x3 matrix of type CV_32FC1 (32-bit floating-point, 1 channel)
88+
cv::Mat mat(3, 3, CV_32FC1);
89+
90+
// Access and modify elements
91+
mat.at<float>(0, 0) = 1.0f;
92+
mat.at<float>(1, 1) = 2.0f;
93+
// ... and so on
94+
95+
// The actual type of elements is known at runtime
96+
}
97+
```
98+
99+
In this example, `cv::Mat` erases the type of its elements (floats, in this case) but still allows type-safe access through the `at` method, which is a templated function.
100+
101+
### Benefits in OpenCV
102+
103+
The use of type erasure in OpenCV, particularly in the `cv::Mat` class, provides several advantages:
104+
105+
- **Flexibility**: It allows a single class (`cv::Mat`) to handle a wide range of image and matrix types.
106+
- **Ease of Use**: Users can work with different types of images and matrices without worrying about the specifics of their storage.
107+
- **Performance**: It enables efficient memory management and optimized performance for image processing operations, as the library can handle different types optimally.
108+
109+
However, it's important to use the `cv::Mat` class and similar constructs correctly to avoid type mismatches and runtime errors. The design of `cv::Mat` showcases how type erasure can be used to create flexible and efficient libraries in domains like image processing and computer vision.
110+
111+
1112

2-
Refs: [1](https://www.youtube.com/watch?v=jKt6A3wnDyI)

0 commit comments

Comments
 (0)