Type erasure allows you to hide type information. This promotes flexibility and code reuse in C++. You can achieve type erasure with interfaces and inheritance. Here’s a simple example:
#include
#include
using namespace std;
class Base {
public:
virtual void draw() = 0;
};
class Circle : public Base {
public:
void draw() override { cout << "Circle" << endl; } }; int main() { unique_ptr shape = make_unique();
shape->draw(); // Outputs Circle
return 0;
}
}
In this example, `Base` is an interface for different shapes. Type erasure allows dynamic type handling.
Leave a Reply