Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a class level typedef as template argument for the base class?

Assume a templated base class:

template<typename T>class BaseClass;

In other classes I want to inherit from this, where T is a rather complicated type, so I would like to use a typedef. Because I do not want to pollute the namespace I want to have the typedef inside the class definition:

class ChildClass : public BaseClass<MyVeryVeryVeryComplicatedType> {
  typedef MyVeryVeryComplicatedType LocalType;
  ...
}

Now of course I cannot yet use LocalType as the template argument for BaseClass and have to write the complicated definition (MyVeryVeryComplicatedType) twice. (So the answer to the title question is 'No', I guess.)

Question: Is there any way to only have the definition only once but still only defined inside the class (or in a similar way that limits the scope of LocalType)?

Note: I thought about using a macro, but noticed that the result would be the same (or even worse) as having the typedef before the class definition.

Edit: For clarification: I have a base class because I want to want to have several different children which share some functionality. The shared parts only need to know that there is some type T. Since the details of the types used in the child classes have nothing to do with the shared functionalities I think that the base class should not know of these details (in practice, I would have to put a lot of #include statements into the base class to be able to define the typedefs for all child classes). Each child class has a rather different MyVeryVeryVeryComplicatedType.

like image 570
user2296653 Avatar asked Dec 25 '22 09:12

user2296653


1 Answers

Just use a little helper namespace:

namespace ChildClassNamespace {
    typedef MyVeryVeryComplicatedType LocalType;
    class ChildClass : public BaseClass<LocalType> { /* ... */ };
}
using ChildClassNamespace::ChildClass;
like image 160
gha.st Avatar answered Dec 28 '22 07:12

gha.st