Templated classes with nested classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • card
    New Member
    • Jun 2007
    • 10

    Templated classes with nested classes

    Hi everyone,

    I have a question about referencing a nested class contained within a templated class. Of course the best way to show you is by example. Here's my templated classes:
    Code:
    #include <stack>
    
    template <class T>
    class A
    {
    public:
    
        // constructor
        A(const T &zz): z(zz) {}
        T z;
    
        // nested class
        class B
        {
        public:
            // constructor
            B(const T &xx, const T &yy): x(xx), y(yy) {}
            T x;
            T y;
        };
    };
    
    template <class T>
    class Iter
    {
    public:
        Iter(const T &xx): x(xx) {}
        T x;
    
        std::stack< A<T> > aStack;
        std::stack< A<T>::B > bStack;
    };
    As you can see, class A is a templated class and class B is nested within A. I have another templated class called Iter. Within Iter, I have two stacks. One contains objects of A and the other objects of the nested class B contained in A. A simple main program to build the code is below:

    Code:
    #include "nested.H"
    
    int main(int argc, char *argv[])
    {
        A<int> myAObject(5);
        A<int>::B myBOjbect(6,7);
        Iter<int> myIterObject(2);
    
        return 0;
    }
    The build with g++ fails with the following error:

    nested.H:44: error: type/value mismatch at argument 1 in template parameter list for ‘template< cla\
    ss _Tp, class _Sequence> class std::stack’
    nested.H:44: error: expected a type, got ‘A<T>::B’
    nested.H:44: error: template argument 2 is invalid

    As you can see, it doesn't know what to do with A<T>::B in the stack declaration of the templated class Iter. How do I reference this nested class within Iter? Obviously, I can do it in main as shown above. Many thanks.

    -David
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Try changing
    std::stack< A<T>::B > bStack;
    to
    std::stack< typename A<T>::B > bStack;
    Somehow that lets the compiler know A<T>::B is a type, but I have no idea why you have to do it. Template syntax-
    AAAAAAAAAAAAARR RRRRRRRRGGGH!!
    Good luck.

    Comment

    • card
      New Member
      • Jun 2007
      • 10

      #3
      Originally posted by boxfish
      Try changing
      std::stack< A<T>::B > bStack;
      to
      std::stack< typename A<T>::B > bStack;
      Somehow that lets the compiler know A<T>::B is a type, but I have no idea why you have to do it. Template syntax-
      AAAAAAAAAAAAARR RRRRRRRRGGGH!!
      Good luck.
      Thanks boxfish! I've been pulling my hair out for a couple hours. That did the trick.

      Comment

      Working...