What is type erasure in C++?

前端 未结 1 535
鱼传尺愫
鱼传尺愫 2020-12-06 01:06

So I was reading this article about type erasure. But the code in that article seems partially incorrect, for example:

template 
class Anim         


        
相关标签:
1条回答
  • 2020-12-06 02:00

    Here's a very simple example of type erasure in action:

    // Type erasure side of things
    
    class TypeErasedHolder
    {
      struct TypeKeeperBase
      {
        virtual ~TypeKeeperBase() {}
      };
    
      template <class ErasedType>
      struct TypeKeeper : TypeKeeperBase
      {
        ErasedType storedObject;
    
        TypeKeeper(ErasedType&& object) : storedObject(std::move(object)) {}
      };
    
      std::unique_ptr<TypeKeeperBase> held;
    
    public:
      template <class ErasedType>
      TypeErasedHolder(ErasedType objectToStore) : held(new TypeKeeper<ErasedType>(std::move(objectToStore)))
      {}
    };
    
    // Client code side of things
    
    struct A
    {
      ~A() { std::cout << "Destroyed an A\n"; }
    };
    
    struct B
    {
      ~B() { std::cout << "Destroyed a B\n"; }
    };
    
    int main()
    {
      TypeErasedHolder holders[] = { A(), A(), B(), A() };
    }
    

    [Live example]

    As you can see, TypeErasedHolder can store objects of an arbitrary type, and destruct them correctly. The important point is that it does not impose any restrictions on the types supported(1): they don't have to derive from a common base, for example.


    (1) Except for being movable, of course.

    0 讨论(0)
提交回复
热议问题