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

Discussion in 'C++' started by Martin Magnusson, Oct 8, 2004.

  1. 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;
    }
     
    Martin Magnusson, Oct 8, 2004
    #1
    1. Advertisements

  2. Martin Magnusson

    JKop Guest

    Martin Magnusson posted:

    j is not a compile time constant.

    -JKop
     
    JKop, Oct 8, 2004
    #2
    1. Advertisements


  3. 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
     
    John Harrison, Oct 8, 2004
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.