e.jahandar
e.jahandar

Reputation: 1763

Using template specializing for hierarchical class construction

Suppose we have a class named DTOBase which contains some declarations, some times i need DTOBase with extra declarations based on given template like this :

class DTOBase {
   /* DTOBase Declarations */
}

template<typename EntityType>
class DTOBase {
     /* DTO Base Declarations */
     /* Extra declarations for EntityType */
}

Now using classes:

DTOBase dto;
/* using with DTOBase members */


DTOBase<SomeEntity> dto;
/* using with DTOBase members and extra templated members */

I create a private base class and then created two version of DTOBase (non templated and templated one), but i think its possible to do it better way, eg. using C++11 template specialization or something like this.

Is it possible to declare a templated class, which inherits members from its non templated version?

Upvotes: 0

Views: 61

Answers (1)

Personally I'd do it like this:

template<class EntityType>
struct DTOBaseExtraMembers {
  // Additional members;
};

template<>
struct DTOBaseExtraMembers<void> {}; // Empty

template<typename EntityType = void>
class DTOBase : DTOBaseExtraMembers<EntityType> {
     /* DTO Base Declarations */
};

The above has the distinct advantage of being subject to the empty base optimization. A base class with no members is optimized on many compilers to not add onto the object size. So the members of the object you get for the "base case" are the same as in your example.

You also get a somewhat uniform representation. The base case is named with DTOBase<> and the extra features added with DTOBase</*Some type*/>;

You can tweak the layout of DTOBase by specializing DTOBaseExtraMembers. Which may spare you possible repetition in fully specializing DTOBase itself.

The downside is that the object layout is different to what you originally had. The extra members will likely come first.


But given the comment you provided to your question. The easiest answer it probably this:

template<class Entity>
class DTODerived : public DTOBase  {
   //Extra stuff
};

The name change is mandatory if you intend to have them exist in the same namespace. You can't have a templated DTOBase if there already is a non-templated one.

Upvotes: 1

Related Questions