LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Template class with a template member... (https://www.linuxquestions.org/questions/programming-9/template-class-with-a-template-member-293157/)

Nicholas Bishop 02-21-2005 05:21 PM

Template class with a template member...
 
I am trying to create a template class that passes its template down to a member that is also a template class, as in this example:
Code:

#include <list>

template< typename T > class Foo
{
public:
        Foo()
        {
                std::list< T >::iterator i;

                // Do stuff
        }
private:
        std::list< T > bar;
};

Compiling (with g++ 3.4.1) gives this error:
vu.cc: In constructor `Foo<T>::Foo()':
vu.cc:8: error: expected `;' before "i"

What is the correct way to do something like this?

Nicholas Bishop 02-21-2005 05:42 PM

Well, I think I've found a solution:

Code:

#include <list>

template< typename T > class Foo
{
public:
        Foo()
        {
                typename std::list< T >::iterator i;
                for( i = bar.begin(); i != bar.end(); i++ )
                {
                        // Do stuff
                }
        }
private:
        std::list< T > bar;
};

But I don't understand why this is necessary...

dakensta 02-21-2005 06:57 PM

Because the compiler doesn't know whether ::iterator is a type or a value, so you need to give it a helping hand.

Code:

template <typename T>
struct some_class
{
    typedef T value_type;  // a type
    static T  value;  // a value
};

template<typename U>
void some_func(U u)
{
    U::value_type v = U::value;      // confused
    typename U::value_type w = U::value; // better
}

I don't have 3.4.1 to hand but didn't you get some warnings like "implicit typename is deprecated"?

HTH

Nicholas Bishop 02-21-2005 08:27 PM

No, I didn't get any other messages from the compiler.

Thanks for the explanation, it makes a lot more sense now.


All times are GMT -5. The time now is 08:38 PM.