Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using template argument of base class in 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 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:

  1. Also templating the derived classes on n, and then using typedef. This way, the derived classes know n:

    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 DerivedTemplateX makes sense for nothing but n=X, so this feels like abusing the template paradigm.

  2. Using a static const member to store n in Base, 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 (nn vs. n). Also, I'm not sure whether this will allow me to use nn as 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?

like image 838
Roman Avatar asked Nov 19 '25 17:11

Roman


1 Answers

The standard practice is to use an uppercase letter for the template parameter, then a static const value in lowercase:

template<int N>
class Base {
protected:
  static const int n = N;
  ...
};

Then you use the lowercase static const value n everywhere - don't use N anywhere else.

Also, I'm not sure whether this will allow me to use nn as a template argument for members of the derived classes.

It is a constant expression and so it can be used as a template argument.

like image 173
Pubby Avatar answered Nov 22 '25 08:11

Pubby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!