nontype (int 변수) 템플릿 매개 변수에 문제가 있습니다.
함수에 상수 int 변수를 전달하고 함수가 템플릿을 인스턴스화하도록 허용 할 수없는 이유는 무엇입니까?Nontype 템플릿 매개 변수
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
}
잘하지 : 컴파일러는 말한다, 오류 : 'j는'이것은 내가 함께 결국 무엇
- 편집
상수 표현에 나타날 수 없습니다. 어쩌면 누군가 그것을 사용할 수도 있고 누군가 더 좋은 방법을 제안 할 수도 있습니다.
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);
}
+1 좋은 질문입니다! – Nawaz
잠깐. 템플릿 인수는 컴파일 타임에 컴파일러가 알아야하기 때문입니다. –