kooldart kooldart - 1 year ago 56
C++ Question

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

Okay so I'm creating my very own Entity-Component System, and I'm stuck at the AddComponent Entity method, which adds components to the Enity, here is how it looks:

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

this works fine, but what if i have a Component constructor ? Like so

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

Vector3f Position;
Vector3f Rotation;
Vector3f Scale;

What I'm trying to achieve is something like this:

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

How do I accept Transform's method parameters as AddComponent method parameters, and achieve something like that above ?

Answer Source

This is the most simplest use case for a parameter pack.

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

Requires at least C++11.