-1

I am trying to inherit a template in C++. This template is using a namespace NSA, the Child Class has also a namespace called NSB. I want to access the protected variables of the template inside a third Class. But I don't know how.

Those are headers:

NSA{
    template <typename T> class A{
    protected:
       unsigned int my_var;
    }
}

NSB{
    class B{ #Don't know how to inherit template A
    ...
    }
}

Inside the cpp file of class C (all header files are included)

using namespace NSA;
NSB{
    unsigned int x = my_var #Get an error. Unidentified
    ...
} 

Thank you.

2 Answers2

1

You can't derived from a template; you can only derive from a class. So class B has to be derived from an instantiation of A:

class B : public A<int> {
};

If you want B to be a template you have to say so:

template <class Ty>
class B : public A<Ty> {
};

In either case, accessing members of the base class is a bit tricker than with an ordinary class, because a template can be specialized, and members declared in the template itself might not exist in a particular specialization. So you have to say that you're talking about a member:

class B : public A<int> {
    unsigned f() { return A<int>::my_var; }
};

Here's another way to say the same thing:

class B : public A<int> {
    unsigned f() { return this->my_var; }
};
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

Skipping the 'C' mumbo jumbo, (which you didn't explain clearly)

I believe this is what you are looking for :

namespace NSA{
    template <typename T> class A{
    protected:
       unsigned int my_var;
    };
}

namespace NSB{
    class B : public NSA::A<int> {
                        //  ^^^ some type or make class B as template 
    //...

    unsigned int x = my_var;
    };
}
P0W
  • 46,614
  • 9
  • 72
  • 119