Template syntax question

Started by
3 comments, last by iMalc 12 years, 7 months ago
Hi guys,

I know there are some template wizards around here so hopefully someone can help :-) I have a simple code example which I can't get to compile on both VS2010 and GCC. I can make simple changes to allow it to compile on either platform, but I haven't found the one correct solution which works on both. See the two commented lines in the code below:

template <typename Type>
class Base
{
public:
template <typename NestedType>
class Nested
{
};
};

template <typename Type>
class Derived : public Base<Type>
{
public:
class Nested : public Base<Type>::Nested< int > //This line works on VS2010
class Nested : public Base<Type>::template Nested< int > //This line works on GCC
{
};
};

int main(int argc, char** argv)
{
Derived<int>::Nested nested;
return 0;
}


In both cases, the line which works on one platform does not work on the other. If I get it the wrong way round the VS2010 error is:

error C2955: 'Base<Type>::Nested' : use of class template requires template argument list

And the GCC error is:

main.cpp:17: error: non-template ‘Nested’ used as template
main.cpp:17: note: use ‘Base<Type>::template Nested’ to indicate that it is a template


Any ideas what the correct syntax is?!

Thanks!
Advertisement
AFAICT the correct syntax is the one gcc accepts. You can get something that compiles with both by adding a typedef:

typedef Base<Type> BaseT;
class Nested : public BaseT::template Nested< int >
Great, thanks! That solution does indeed seem to work on both compilers.
For the benefit of anyone else who comes across this thread it's worth pointing out that I have run into some difficulties with the above approach. My real world example is obviously more complex that what I showed above, but I have applied the same principles and got it to compile successfully on both GCC and VS2010. However, I have since discovered that it causes problems with VS2008.

In particular, with VS2008 is causes an internal compiler error but only if compiling with the /Gm (Enable Minimal Rebuild) compiler option. Without this option it appears to work fine, but as VS2008 projects have this on by default it can be a problem.

I think for now I'll stick with preprocessor defines to use the right line for each platform, but I may revisit this in the future.
Thanks for the update. Nested templated classed have historically been problematic for visual studio.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement