This question was inspired by this other question. While trying to answer that question, I understood that I have a lot of questions myself. So... Consider the following:
struct S1
{
enum { value = 42 };
};
template <class T> struct S2
{
typedef S1 Type;
};
template <class T> struct S3
{
typedef S2<T> Type;
};
template <class T> struct S4
{
typedef typename T::Type::Type Type; //(1)//legal?
enum {value = T::Type::Type::value }; //(2)//legal?
};
int main()
{
S4<S3<S2<S2<S1> > > >::value;
}
This compiles successfully with MSVC9.0 and Online Comeau. However, what's bothering me is that I don't understand what typename
refers to in (1) and why wouldn't we need typename
in (2).
I have tried these 2 syntaxes (syntaces?) of what I think it should be both of which fail on MSVC:
typedef typename T::typename Type::Type Type;
enum {value = typename T::typename Type::Type::value };
and
typedef typename (typename T::Type)::Type Type;
enum {value = (typename (typename T::Type)::Type)::value };
Of course, a workaround is to use consecutive typedef
s like this:
typedef typename T::Type T1;
typedef typename T1::Type Type;
enum { value = Type::value};
Good style left aside, do we syntactically have to use the workaround I mentioned?
The rest is just an interesting example. No need to read. Not that relevant to the question.
Please note, that although MSVC accepts the original strange syntax without multiple typename
s(I mean (1) and (2)), it leads to strange behavior as in the mentioned question. I think I'll present that example in concise form here as well:
struct Good
{
enum {value = 1};
};
struct Bad
{
enum {value = -1};
};
template <class T1, class T2>
struct ArraySize
{
typedef Bad Type;
};
template <class T>
struct ArraySize<T, T>
{
typedef Good Type;
};
template <class T>
struct Boom
{
char arr[ArraySize<T, Good>::Type::value]; //error, negative subscript, even without any instantiation
};
int main()
{
Boom<Good> b; //with or without this line, compilation fails.
}
This doesn't compile. The workaround I mentioned solves the problem, but I am sure the problem here is my initial question - missing typename, but you don't really know where to stick one. Thanks very much in advance.