c++templatesinheritancetemplate-specializationderived-class

Making a class template that is dependent on another template


So I have a set of classes that are all derived from a base class RigidBody (NOTE: In the following code Tp is used to specify a precision type (e.g. float), while Tc is ued to a specify a color type (e.g. RGB):

template <typename Tp>
class RigidBody {
    ...
}

These classes are Model, Assembly, Light, etc. Below is an example of Model

template <typename Tp, typename Tc>
class Model : public RigidBody<Tp> {
    ...
}

I now need to write a templated Instance class that acts as a wrapper around all of these classes, and is also derived from RigidBody. What I currently have is this:

template <typename Tp, typename ObjectType>
class Instance : public RigidBody<Tp> {
    ...
};

While this works, it feels clunky to need to specialize using (for example)

Instance<float, Model<float,RGB>>

Because the float is redundant. I'd much rather just be able to use Instance<Model<float,RGB>>

I've read about "template template" syntax but that doesn't seem to address my issue. I've tried:

template <template<typename Tp,typename Tc> typename ObjectType>
class Instance : public RigidBody<Tp> {
    ...
}

But this does not work because Tp is an undeclared identifier for the actual body of the class declaration.

Is there a way of getting the behavior how I would like? Under no circumstance would I ever want to allow the instance to have a different precision from whatever object it is wrapping.


Solution

  • Make class Instance accept just <typename ObjectType>.

    Add using foo = Tp; to class RigidBody (it must be public or protected).

    Then you can use typename ObjectType::foo in Instance to access that type:

    template <typename Tp>
    class RigidBody
    {
      public:
        using foo = Tp;
    };
    
    template <typename Tp>
    class A : public RigidBody<Tp> {};
    
    template <typename ObjectType>
    class Instance : public RigidBody<typename ObjectType::foo> {};