什么是类型擦除(Type Erasure)?以及如何在 C++ 中实现?
作为一名 C++ 程序员,你可能会遇到需要在运行时动态分配对象的情况。在这种情况下,你可能需要使用类型擦除(Type Erasure)技术。在这篇博文中,我们将学习什么是类型擦除,以及如何在 C++ 中实现。
什么是类型擦除?
类型擦除是一种在运行时动态分配对象的技术。它允许你在编译时不知道对象的类型,但在运行时仍然可以使用这个对象。这种技术通常用于实现一种Called 函数,它可以接受任意类型的参数,并且可以在运行时动态分配这些参数。
类型擦除的实现
在 C++ 中,类型擦除可以通过使用虚函数和虚继承来实现。这种技术通常称为虚函数表(Virtual Function Table)或虚表(vtable)。
以下是一个简单的类型擦除的示例代码:
#include <iostream>
#include <memory>
#include <vector>
// Base class with a virtual function
class Base
{
public:
virtual void call() = 0;
};
// Derived class with a concrete implementation
class Derived : public Base
{
public:
void call() override
{
std::cout << "Called Derived::call()" << std::endl;
}
};
// Function that accepts a Base pointer
void callFunction(std::shared_ptr<Base> ptr)
{
ptr->call(