Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to inherit an alias template?

Tags:

c++

templates

I have a template base class:

template<class EntityManager>
class System {
public:
  virtual void Update(EntityManager& entity_manager, double dt) = 0;
protected:
  template<typename T> using Component = typename EntityManager::template Component<T>;
};

I'd like to use Component<T> in my derived template classes.

I've tried to instead have System declare Component as its own class, but when I try to reference it, the compiler returns, 'Component' was not declared in this scope.

Any suggestions?

Edit: Inteded Usage:

template class<typename EntityManager>
class MovementSystem : public System<EntityManager> {
public:
  virtual void Update(EntityManager& entity_manager, double dt) {
    Component<Position> position_component; // I'd like to use Component<T> here.
  }
};
like image 573
Charles W Avatar asked Jan 03 '15 21:01

Charles W


1 Answers

In a derived class template (which is most probably what you mean) you can do

using Component = typename System<T>::Component;

where T is some appropriate type in the derived class.


Dealing with a template you can do this:

template< class U > using Component = typename System<T>::template Component<U>;

as noted by dyp in a comment.

Details depend a bit on the context, here's a concrete example for your code given in edit of the post:

class ET
{
public:
    template< class Type >
    struct Component {};
};

template<class EntityManager>
class System {
public:
  virtual void Update(EntityManager& entity_manager, double dt) = 0;
protected:
  template<typename T> using Component = typename EntityManager::template Component<T>;
};

template< class EntityManager >
class MovementSystem : public System<EntityManager> {
public:
#ifndef DONTFIXIT
  template< class T > using Component = typename EntityManager::template Component< T >;
#endif

  virtual void Update(EntityManager& entity_manager, double dt) {
    Component<int> position_component; // I'd like to use Component<T> here.
  }
};

auto main() -> int
{
    MovementSystem< ET > ms;
}

There's no easy way to do this, sorry.

This is clearly an area where the core language has the potential to much better support the programmer, avoiding restating a name over and over again.


The rationale for the language being as it is, is that some specializations of System may not necessarily define a Component type, or an accessible one.

With the using you enable the compiler to diagnose lack of such a type, up front.

like image 171
Cheers and hth. - Alf Avatar answered Oct 11 '22 10:10

Cheers and hth. - Alf