C++ 通用组件系统

C++ Generic component system

我正在尝试在 C++ 中实现像 Unity3D 中那样的实体组件。我想做的是可以在 C# 中轻松实现的事情:

public T GetComponent<T>() where T : Component
    {
        foreach (Component component in _components)
        {
            if (component is T)
                return component as T;
        }
        
        return null;
    }

然而,当我尝试编写如下所示的 C++ 等价物时:

template <class T>
Component& getComponent()
{
    for (auto component : componentList)
    {
        if (dynamic_cast<T>(*component) != nullptr) 
        {
            return *component;
        }
    }
}

我收到以下编译器错误:'T':dynamic_cast 的目标类型无效。
有没有不同的方法来解决这个问题?

dynamic_cast 要求被转换的表达式和被转换为的类型是 指针 (或引用)。

您不能在不使用指针或引用的情况下使用 dynamic_cast

所以解是大概:

if (dynamic_cast<T*>(component) != nullptr)