Question

I'm having some trouble with C++: I have a class Primitive, it contains a member variable of an abstract buffer class..

Concrete buffer classes exist in many different forms for many different vertex types.. point-colour-normal, point-texcoord-normal, point-normal, point, etc.

I need to be able to add any type of vertex to a buffer held by classes that derive from primitive, for example quadsets, tri-lists, etc.

class Buffer {
   //...
   template<class T> 
   virtual void Add(const T&) = 0; // nope! Not compilable
   virtual void Add(boost::any&) = 0; // I have been told no boost allowed either..
}

template<class T>
TypedBuffer : public Buffer {
  //..
public:
  std::vector<T> buffer;
public:
  virtual void Add( const T& elem ) { buffer.push_back( elem ); }
}

class Primitive {
protected:
  Buffer vertices;
public:
  // How can I allow this to happen? \/
  virtual void AddVert( const vec3& v) { vertices.Add( v ); }
}

class QuadSet : public Primitive { /*QuadSet Specifics..*/ }

void main(){
   QuadSet q;
   q.Add( COLOURED_VERT(vec3(1, 2, 3), vec3(0.5,0.5,0.5) ) );
}

Please Help!

Was it helpful?

Solution

When facing a similar problem, I ended up using type eraser. However in my example it requires to use something like reinterpret_cast:

class Buffer {
  virtual void Add(const void*) = 0;
};

template <typename T>
class TypedBuffer: Buffer {
  virtual void Add(const void* e) { buffer.push_back(*static_cast<T*>(e)); }
};

class Primitive {
  virtual void AddVert(const vec3& v) { vertices.Add(reinterpret_cast<const void*>(&v)); }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top