"Non-constant" constant can't be used as template argument

  • Thread starter Martin Magnusson
  • Start date
M

Martin Magnusson

It seems that the following code is not valid, but I need to find a
workaround. Both gcc and Comeau tells me that j can't be used as a
template argument, even though it's declared as a const unsigned. Is
there a way to get around this?

template< unsigned M >
class Tree
{
public:
Tree()
{
for (unsigned i = 0; i < M; ++i)
{
const unsigned j = i;
Compare<j> c; // j cannot be used as template argument
}
}

private:
template< unsigned N >
class Compare
{
public:
bool operator()( int i1, int i2 )
{ return i1 < i2; }
};
};

int main()
{
Tree<3> t;
return 0;
}
 
J

JKop

Martin Magnusson posted:
It seems that the following code is not valid, but I need to find a
workaround. Both gcc and Comeau tells me that j can't be used as a
template argument, even though it's declared as a const unsigned. Is
there a way to get around this?

template< unsigned M >
class Tree
{
public:
Tree()
{
for (unsigned i = 0; i < M; ++i)
{
const unsigned j = i;
Compare<j> c; // j cannot be used as template argument
}
}

private:
template< unsigned N >
class Compare
{
public:
bool operator()( int i1, int i2 )
{ return i1 < i2; }
};
};

int main()
{
Tree<3> t;
return 0;
}


j is not a compile time constant.

-JKop
 
J

John Harrison

Martin Magnusson said:
It seems that the following code is not valid, but I need to find a
workaround. Both gcc and Comeau tells me that j can't be used as a
template argument, even though it's declared as a const unsigned. Is
there a way to get around this?


The way round it is to use loop unrolling.

template< unsigned M >
class Tree
{
public:
Tree()
{
UnrolledLoop<0, M>::execute();
}
};

template< unsigned I, unsigned M >
struct UnrolledLoop
{
static void execute()
{
Compare<I> c;
UnrolledLoop<I + 1, M>::execute();
}
};


template< unsigned I >
struct UnrolledLoop<I, I>
{
static void execute()
{
}
};

This is completely untested but hopefully you get the idea.

john
 

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,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top