Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typedef and typename inside a template

I want to define a type name in a templated class that I can use elsewhere to refer to the type of a member in the class.

template <class T>
class CA
{
public:
    //typedef typename T::iterator iterator_type;
    typedef typename T ElementType1; // compile error on this line
    //typedef T ElementType2;

    T m_element;
};

and use it like this:

template <class T>
class CDerived : public CBase<typename T::ElementType1>
{
 //...
};

and declare objects like:

typedef CDerived<CA> MyNewClass;

Is this not possible? I have some code that compiles correctly under VS2010 but not under Xcode that uses the line:

typedef typename T ElementType1;

Apparently the compiler is expecting a qualified name after typename but I don't see how there can be one for the template type.

I dont understand the difference between ElementType1 and ElementType2 in this context.

I looked at many questions on stack overflow but most seemed to refer to only the kind of declaration like iterator_type in my example.

like image 434
Robotbugs Avatar asked Feb 22 '23 03:02

Robotbugs


1 Answers

The compiler already knows T is a type (class T), so you don't need the typename qualifier in the first case. OTOH, the compiler doesn't know in advance that T::ElementType1 is a type; it depends on what T ends up being.

like image 92
Marcelo Cantos Avatar answered Mar 08 '23 06:03

Marcelo Cantos