Search⌘ K

- Examples

Explore C++ design examples illustrating type erasure using both object-oriented programming and template techniques. Understand the advantages and drawbacks of each method, including virtual dispatch and template flexibility. This lesson helps you grasp how to implement polymorphism efficiently with clean design.

Example 1: Type Erasure Using Object-Oriented Programming

C++
// typeErasureOO.cpp
#include <iostream>
#include <string>
#include <vector>
struct BaseClass{
virtual std::string getName() const = 0;
};
struct Bar: BaseClass{
std::string getName() const override {
return "Bar";
}
};
struct Foo: BaseClass{
std::string getName() const override{
return "Foo";
}
};
void printName(std::vector<BaseClass*> vec){
for (auto v: vec) std::cout << v->getName() << std::endl;
}
int main(){
std::cout << std::endl;
Foo foo;
Bar bar;
std::vector<BaseClass*> vec{&foo, &bar};
printName(vec);
std::cout << std::endl;
}

Explanation

The key point is that you can use instances of Foo or Bar instead of an instance for BaseClass. std::vector<BaseClass*> (line 35) has a pointer to BaseClass. Well, actually it has two pointers to BaseClass (derived) objects and it is a vector of such ...