PhilippJS
PhilippJS

Reputation: 51

How to access template parameters from a derived class?

I have a

template <int N> class Base

and

class Derived : public Base<1>

... is there a way to access the int N from inside the definition of a Derived::myMethod() (instead of getting the compiler error "use of undeclared identifier 'N'")?

More precisely, I would like to do

void Derived::myMethod() {
   for (int n=0; n<N; n++) { ...

Upvotes: 5

Views: 1813

Answers (3)

clanmjc
clanmjc

Reputation: 299

This is what I meant from my comment above:

class Base{
  public:
     Base(int value = 1) : value_(value){}  //don't need to use default param but can
  private:
     int value_
}

class Derived : public Base
{}

Why templatize N? Do you need to specialize the entire class? An alternative would be "virtualizing" non member functions that are called from the template based on the criteria you set as "specialization".

Edit: Partial specialization of a method in a templated class

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

One other option is you could template the derived class:

template <int N>
class Derived : public Base<N>
{
    void myMethod()
    {
        for (int i = 0; i < N; ++i)
        //
    }
};

Upvotes: 1

The template argument has the scope of the template, but you can define a nested constant in the template that can be used by derived classes:

template <int N> class Base {
public: // or protected:
   static const int theN = N;
};

Upvotes: 5

Related Questions