开发者

template <typename T> perculating all through the code

I templatized a class earlier and as a result of this templatization, all classes that received objects of this newly templated type require templating as well, even where the templatization is completely irrelevant.

So:

  • class Shape is the base class for class Sphere, Cube, Model
  • Each Shape contains a Mesh
  • Mesh has now been templatized to allow for basically the VertexBuffer to have a parameterized type:

So:

template <typename T> struct Mesh
{
    VertexBuffer<T> verts ; // Mesh needs to be templated to allow
    // the vertex buffer to be templated as well
} ;

So now the class that contains the Mesh (base class Shape) needs to be templated as well:

template <typename T> class Shape
{
    Mesh<T>* mesh ;
} ;

And now, all the methods anywhere in the code need to be templated as well, even where that templatization i开发者_如何学Cn no way affects the code (ie that code has no business with the vertex type of the Mesh member)

So for example, the octree node:

// An octree node
template <typename T> struct ONode // but this class doesn't really benefit
                                   // from templatization
{
    AABB bounds ;
    ONode* parent ; // facilitate movement thru the tree
    ONode* children[8]; // cells, octants, cubelets
    Shape<T>* objects ;    // for the purposes of the Octree,
                        // But ALL SHAPES BEHAVE THE SAME. <T> serves no purpose

This is a really nasty artifact and I'm not sure how to stop the perculation of templatization at an earlier point, or if templatization was a correct choice now that I see how much needs to be templatized.


I would suggest you create a non-templated base class for Mesh (or VertexBuffer, whichever makes the most sense) that exposes the functionality that doesn't depend on the template, and use that in other places. For example:

class MeshBase
{
    // Functionality that doesn't depend on the template type.
};

template<typename T>
class Mesh : public MeshBase
{
    // Functionality that does depend on the template type.
};

This does mean that you may more frequently need to deal with dynamically allocated values of this type and pass them around as pointers, but some judicious use of smart pointers should alleviate that burden.


In general, there is a certain friction between using object oriented principles and generic programming principles, some of which you've discovered here. Whenever this happens, you essentially need a class that can hold the value of multiple generic types and models the common behavior, without the consumer needing to know the templated type. Sometimes, this can be done even if the types have no common base. This technique is called type erasure and this article by Thomas Becker provides some insight into this matter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜