Nontype Template Parameter

I'm having problems with the nontype (int variable) template parameter.
Why can't I pass an int constant variable to a function and let the function instantiate the template?

template<int size>
class MyTemplate
{
  // do something with size
};

void run(const int j)
{
  MyTemplate<j> b; // not fine
}
void main()
{
  const int i = 3;
  MyTemplate<i> a; // fine;
  run(i); // not fine
}

Not bad: the compiler says error: 'j' cannot appear in constant expression

  • EDIT

Here is what I ended up with. Maybe someone can use it, someone can suggest a better way.

enum PRE_SIZE
{
    PRE_SIZE_256 = 256,
    PRE_SIZE_512 = 512,  
    PRE_SIZE_1024 = 1024,
};

template<int size>
    class SizedPool : public Singleton< SizedPool<size> >
{
public:
    SizedPool()
        : mPool(size)
    {
    }
    void* Malloc()
    {
        return mPool.malloc();
    }

    void Free(void* memoryPtr)
    {
        mPool.free(memoryPtr);
    }

private:
    boost::pool<>       mPool;
};

template<int size>
    void* SizedPoolMalloc()
    {
        return SizedPool<size>::GetInstance()->Malloc();
    }

template<int size>
    void SizedPoolFree(void* memoryPtr)
    {
        SizedPool<size>::GetInstance()->Free(memoryPtr);
    }

void* SizedPoolMalloc(int size)
{
    if (size <= PRE_SIZE_256)
        return SizedPoolMalloc<PRE_SIZE_256>();
    else if (size <= PRE_SIZE_512)
        return SizedPoolMalloc<PRE_SIZE_512>();
}


void toRun(const int j)
{
    SizedPoolMalloc(j);
}
void Test17()
{
    const int i = 3;
    toRun(i);
}
+3
source share
3 answers

. , - ; . , . j run() , run(), .

void run(const int j)
{
    // The compiler can't know what j is until the program actually runs!
    MyTemplate<j> b;
}

const int i = 3;
run(i);

, "j ".

, , i .

const int i = 3;
// The compiler knows i has the value 3 at this point,
// so we can actually compile this.
MyTemplate<i> a;

, .

run() , MyTemplate :

template<int j>
void run()
{
    MyTemplate<j> b;
}

const int i = 3;
run<i>();
+9

, ++ :

const int a = 5;
MyTemplate<a> foo; // OK

const int b = rand();
MyTemplate<b> foo; // Not OK.

- . ++ , (ICE). - . ++ (const int), ICE.

void run(const int j) - . . .

, . , .

+2

Because j must be known at compile time. In your example, this is not the case.

+1
source

All Articles