Home > Net >  Alias within a class template
Alias within a class template

Time:12-03

For following class

template<typename T>
class test { 
   public:
   using unit = std::micro;    
};

How do I access unit like test::unit without having to specify the template argument or make it a template alias. Please note that inserting a dummy template argument like e.g . int is not an option since some template classes cannot be instantiated with such types.

CodePudding user response:

First, it is important to understand that really everything in the template depends on the template parameter T. Even if it looks like it does not on first sight.

Consider that there can be a specialization:

template <>
struct foo< bar > {};

Now there is a foo instantiation that has no member alias. And thats the reason why foo::unit cannot work the way you wish.


Please note that inserting a dummy template argument like e.g . int is not an option since some template classes cannot be instantiated with such types.

I don't understand this argument. If there is a different class template (there are no template classes, they are called class templates) which cannot be instantiated with int then choose a different default. You need not use the same default for all.

However, as discussed above the approach with using a default argument and then refering to the alias via foo<>::unit is flawed anyhow.


The simple solution is to not have the alias as member:

using unit = std::micro;    
template<typename T> class test { };

On the other hand, if it should be part of the class, it can be moved to a non-template base class:

struct base { using unit = std::micro; }
template <typename T> struct test : base {};
  •  Tags:  
  • c
  • Related