gilgamash
Knight
Greetings all,
ever asked how it might be possible to derive specialized template classes from a base class?
Task: Imagine you want to implement a message logger where the level (debugging, trace, info, warning, etc) of the debugger is given as a template parameter to make it compile time changable. The base class however shall not be instantiable, only the concrete implementations of a logger.
Obstacle: Despite minor differences, the basic logger functions are the same for all the specializations.
We will determine the kind of the debugger by an integer, aiming at int-specialized template. The simple trick is, to implement a virtual non template base class
that cannot be instantiated itself (do not forget to include <string>).
Now, derive the general template class without overriding the virtual function, leaving it not instantiable also:
Finally, go for the specialized variants, for which you implement the virtual functions. For instance:
Viola, the specializations inherit all you want to implement in BaseLogger and only those for which the specialized version include the virtual method (which might also be a dummy) can be instantiated.
G.
ever asked how it might be possible to derive specialized template classes from a base class?
Task: Imagine you want to implement a message logger where the level (debugging, trace, info, warning, etc) of the debugger is given as a template parameter to make it compile time changable. The base class however shall not be instantiable, only the concrete implementations of a logger.
Obstacle: Despite minor differences, the basic logger functions are the same for all the specializations.
We will determine the kind of the debugger by an integer, aiming at int-specialized template. The simple trick is, to implement a virtual non template base class
Code:
class BaseLogger
{
public:
BaseLogger(){};
~BaseLogger(){};
virtual std::string descr()=0;
// whatever you need
};
Now, derive the general template class without overriding the virtual function, leaving it not instantiable also:
Code:
template<int n>
class MyLogger : public BaseLogger
{
public:
MyLogger(){};
~MyLogger(){};
// whatever you need
};
Finally, go for the specialized variants, for which you implement the virtual functions. For instance:
Code:
template<>
class MyLogger<1> : public BaseLogger
{
public:
MyLogger(){};
~MyLogger(){};
std::string descr()
{
return ("[infologger]");
}
// whatever you need
};
Viola, the specializations inherit all you want to implement in BaseLogger and only those for which the specialized version include the virtual method (which might also be a dummy) can be instantiated.
G.