5

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.

Robotbugs
  • 4,307
  • 3
  • 22
  • 30

2 Answers2

5

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • OK cool that answers my question, I need to just use `typedef T ElementType`. Really I wasn't sure if typename should be in there or not. I understand its use in the `CBase`. Here is more info about type name [link](http://pages.cs.wisc.edu/~driscoll/typename.html). It seems like VS2010 accepts the ElementType1 declaration however, but perhaps not gcc. – Robotbugs Dec 13 '11 at 00:35
4

typename can only be used to qualify a qualified name; it doesn't apply the the name immediately following it, but to the qualified name, i.e. in:

typedef typename T::X x;

the typename applies to the X, and not the T. For this reason, it is only legal (in this use) before qualified names. Non-qualified names must be in a context where the compiler can know whether the name is a type or not. (In practice, this is only an issue in types defined in a dependent base class, and these can be qualified.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329