c – 非类型模板参数
发布时间:2020-12-16 10:28:59 所属栏目:百科 来源:网络整理
导读:我遇到了nontype(int variable)模板参数的问题. 为什么我不能将常量int变量传递给函数并让函数实例化模板? templateint sizeclass MyTemplate{ // do something with size};void run(const int j){ MyTemplatej b; // not fine}void main(){ const int i =
我遇到了nontype(int variable)模板参数的问题.
为什么我不能将常量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’不能出现在constant-expression中 >编辑 这就是我最终的结果. 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>(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |