gpt4 book ai didi

c++ - 非类型模板参数

转载 作者:太空狗 更新时间:2023-10-29 19:44:42 27 4
gpt4 key购买 nike

我在使用非类型(整数变量)模板参数时遇到问题。
为什么我不能将常量int变量传递给函数并让函数实例化模板?

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);
}

最佳答案

因为非类型模板参数在编译时需要值。请记住,模板是一种编译时机制;最终可执行文件中不存在模板。还请记住,函数和向函数传递参数是运行时机制。 run() 中的j 参数的值只有在程序实际运行并调用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>();

关于c++ - 非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com