什么是C ++中的类型擦除? [英] What is type erasure in C++?

查看:118
本文介绍了什么是C ++中的类型擦除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在阅读有关类型擦除的文章。但是该文章中的代码似乎部分不正确,例如:

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

template <typename T>
class AnimalWrapper : public MyAnimal
{
    const T &m_animal;

public:
    AnimalWrapper(const T &animal)
        : m_animal(animal)
    { }

    const char *see() const { return m_animal.see(); }
    const char *say() const { return m_animal.say(); }
};

其后是

void pullTheString()
{
    MyAnimal *animals[] = 
    {
        new AnimalWrapper(Cow()), /* oO , isn't template argument missing? */
        ....
    };
}

这些错误使我无法继续阅读本文。

These mistakes discouraged me from reading any further in the article.

无论如何;任何人都可以通过简单的示例来说明C ++中的类型擦除是什么意思吗?

Anyways; can anyone please teach what type erasure in C++ means, with simple examples?

我想了解一下它,以了解 std :: function 可行,但无法解决。

I wanted to learn about it to understand how std::function works, but couldn't get my head around it.

推荐答案

下面是一个非常简单的类型示例删除操作:

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() };
}

[实时示例]

如您所见, TypeErasedHolder 可以存储对象,并正确销毁它们。重要的一点是,它不对所支持的类型施加任何限制(1):例如,它们不必从公共基础派生。

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)当然除了可移动。

这篇关于什么是C ++中的类型擦除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆