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 of the Derived3 member functions, I would like to explicitly use n=3, and inside Derived7, n=7, without hardcoding the numbers, i.e., still referring to something like a template argument n. The following options come to my mind:
-
Also templating the derived classes on
n, and then usingtypedef. This way, the 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 with this is that
DerivedTemplateXmakes sense for nothing butn=X, so this feels like abusing the template paradigm. -
Using a static const member to store
ninBase, and referring to that in the 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 here is that I seemingly can’t use the same identifier (
nnvs.n). Also, I’m not sure whether this will allow me to usennas a template argument for members of the derived classes.
So: how can this be implemented in a non-redundant, efficient way? Maybe using some kind of static const int as a member somewhere?
The standard practice is to use an uppercase letter for the template parameter, then a static const value in lowercase:
Then you use the lowercase static const value
neverywhere – don’t useNanywhere else.It is a constant expression and so it can be used as a template argument.