简体   繁体   中英

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, ie, 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?

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.

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()
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM