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 with typedef

    . Thus, 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 is that DerivedTemplateX

    it only makes sense for n=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 use nn

    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?

+3


source to share


2 answers


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.

+5


source


Does this work for you?



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

class Derived3 : public Base<3> {
    void f()
    {
        std::cout << MyN;
    }
};

class Derived7 : public Base<7> {
    void f()
    {
        std::cout << MyN;
    }
};

int main()
{

}

      

0


source







All Articles