VC6 recursive template enum definition

A

Amon Tse

I have the following code which is unable to compile in VC6:

#include <iostream>

template<size_t target, size_t idx = 0>
struct _Iterator
{
enum
{
value = (target == idx) ? idx : _Iterator<target, idx+1>::value
};
};

int main()
{
std::cout << _Iterator<3>::value << std::endl;
// the expected result is 3
return 0;
}

The compilation error is

fatal error C1202: recursive type or function dependency context too
complex

This likely could be solved if I had switched to use VC7.1. However, I
have no luck that I must use VC6. Could anyone offer me a workaround?
Thanks in advance.
 
V

Victor Bazarov

Amon said:
I have the following code which is unable to compile in VC6:
[...]
This likely could be solved if I had switched to use VC7.1. However, I
have no luck that I must use VC6. Could anyone offer me a workaround?

Please ask compiler-specific questions in the newsgroups dedicated to
those compilers (microsoft.public.vc.language in this case).
 
J

John Carson

Amon Tse said:
I have the following code which is unable to compile in VC6:

#include <iostream>

template<size_t target, size_t idx = 0>
struct _Iterator
{
enum
{
value = (target == idx) ? idx : _Iterator<target, idx+1>::value
};
};

int main()
{
std::cout << _Iterator<3>::value << std::endl;
// the expected result is 3
return 0;
}

The compilation error is

fatal error C1202: recursive type or function dependency context too
complex

This likely could be solved if I had switched to use VC7.1.


Actually no. You have an infinite loop. The problem is that in the line

value = (target == idx) ? idx : _Iterator<target, idx+1>::value

However, I
have no luck that I must use VC6. Could anyone offer me a workaround?


If you were using VC++7.1, you could do it this way:

#include <iostream>

template<size_t target, size_t idx = 0>
struct _Iterator
{
enum
{
value = _Iterator<target, idx+1>::value
};
};

template <size_t target>
struct _Iterator<target, target>
{
enum
{
value = target
};
};

This won't work for VC++6.0 since it doesn't support partial template
specialisation.

As for finding a workaround, it is not clear to me what your code is
attempting to do. Something far simpler like

template<size_t target>
struct _Iterator
{
enum
{
value = target
};
};

will produce an output of 3 from your code in main(). What more do you want?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top