benjist benjist - 1 year ago 78
C++ Question

Templates: Instantiate an object with a member of class type

I've a factory method which creates Mesh objects. A mesh object has a Vertex class member which can be of various flavor (I'd like to create

template<class T>
NewMesh* createMesh(T)
mesh_data* md = new mesh_data;
T* vd = new T;
md->vdata = vd;
NewMesh* mptr = new NewMesh(generateUid());

return mptr;

What I want to achieve is something like this, which should create a Mesh object with a vertex_data_P3_N3 class member for vdata.

Mesh* polym = meshFactory.createMesh(vertex_data_P3_N3);

Rather obviously, this doesn't work and throws "vertex_data_P3_N3".

This works, but it I dislike the syntax:

vertex_data_P3_N3 vd;
Mesh* polym = meshFactory.createMesh(vd);

What's a better way to pass the class type?

Answer Source

The function parameter of createMesh is unused, which is a strong indication of it being redundant.

template<class T>
    NewMesh* createMesh() { ...

Mesh* polym = meshFactory.createMesh<vertex_data_P3_N3>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download