gpt4 book ai didi

c++ - 将类作为模板参数,并将类构造函数的参数作为方法参数的方法

转载 作者:行者123 更新时间:2023-11-30 01:09:18 25 4
gpt4 key购买 nike

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

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

这工作正常,但如果我有一个 Component 构造函数怎么办?像这样

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。

关于c++ - 将类作为模板参数,并将类构造函数的参数作为方法参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com