Using a base class template argument in a derived class
Consider the following situation in C ++:
template<int n>
class Base { ... };
class Derived3 : public Base<3> {
// a complicated body, making use of n=3
};
class Derived7 : public Base<7> {
// a completely different body, making use of n=7
};
Inside member functions, Derived3
I would like to use explicitly n=3
and internally Derived7
, n=7
without hardcoding the numbers, i.e. still referencing something like a template argument n
, the following options come to my mind:
-
See also derived class templates for
n
and later withtypedef
. Thus, derived classes known
:template<int n> class DerivedTemplate3 : public Base<n> { ... }; typedef DerivedTemplate3<3> Derived3; template<int n> class DerivedTemplate7 : public Base<n> { ... }; typedef DerivedTemplate7<7> Derived7;
The problem is that
DerivedTemplateX
it only makes sense forn=X
, so it seems like an abuse of the template paradigm. -
Using a static constant member to store
n
in,Base
and referencing that in derived classes:template<int n> class Base { protected: static const int nn = n; ... }; class Derived3 : public Base<3> { // refer to nn=3 }; class Derived7 : public Base<7> { // refer to nn=7 };
The problem is I can't seem to use the same identifier (
nn
vs.n
). Also, I'm not sure if this will allow me to usenn
as a template argument for derived class members.
So: how can this be implemented without excess, efficiently? Maybe using some kind static const int
as a member?
source to share
It is standard practice to capitalize on the template parameter, then lowercase a static const value:
template<int N>
class Base {
protected:
static const int n = N;
...
};
Then you use the string static const value n
everywhere - don't use n
anywhere else.
Also, I'm not sure if I would allow nn to be used as a template argument for derived class members.
It is a constant expression, so it can be used as a template argument.
source to share