方法,该方法接受类作为模板参数,并接受类构造函数的参数作为方法参数

method that takes a class as a template parameter, and takes the parameters of the classes constructor as method parameters

本文关键字:方法 参数 构造函数      更新时间:2023-10-16

好了,我正在创建我自己的实体组件系统,我被困在AddComponent Entity方法,它将组件添加到实体中,下面是它的样子:

template <typename T>
void AddComponent() {
    NumOfComponents++;
    AllComponents.push_back(new T());
}

这个工作得很好,但如果我有一个组件构造函数呢?就像

class Transform : public Component
{
public:
    Transfrm(Vector3f newPosition, Vector3f newRotation, Vector3f newScale) : Component("Transfrm") {};
    Vector3f Position;
    Vector3f Rotation;
    Vector3f Scale;
    ~Transfrm();
};

我想要达到的是这样的:

Entity ent1;
Vector3f Pos, Rot, Scl;
ent1.AddComponent<Transform>(Pos, Rot, Scl); // This is currently not possible

我如何接受Transform的方法参数作为AddComponent方法参数,并实现类似于上面的东西?

这是参数包最简单的用例。

template <typename T, typename ...Args>
void AddComponent(Args && ...args) {
    NumOfComponents++;
    AllComponents.push_back(new T(std::forward<Args>(args)...));
}

要求至少c++ 11