2016-11-14 142 views
1

好吧,我创建了我自己的实体组件系统,并将其锁定在AddComponent实体方法中,添加组件到Enity,这里是它的外观:将类作为模板参数,并将类构造函数的参数作为方法参数的方法

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 

如何接受变换的方法参数AddComponent方法参数,实现类似的东西上面?

回答

5

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

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

需要至少C++ 11。

+0

你好代码你告诉我是给我两个错误的是“无效AddComponent(参数&& ..args){”错误行24 \t C3484 \t语法错误:预期“ - >”的返回类型之前 错误\t C3613 \t' - >'(假设为'int')后缺少返回类型24 – kooldart

+0

小写字母错误。一段时间不见了。 –

+0

不要固定它,用3个虚线参数替换“..args”:“......参数” – kooldart