C++ 模板类的模板参数
我有一些模板类池:C++ 模板类的模板参数,c++,templates,C++,Templates,我有一些模板类池: template<int a> class Pool{} 模板 类池{} 现在,我有了另一个类,其中我将池的对象指针作为参数传递: template<int a, Pool<a> &pool> class Point{} template您不能只使用一个static const成员来存储Pool的模板参数吗 #include <stdio.h> template<int i> struct Pool
template<int a>
class Pool{}
模板
类池{}
现在,我有了另一个类,其中我将池的对象指针作为参数传递:
template<int a, Pool<a> &pool>
class Point{}
template您不能只使用一个static const成员来存储Pool的模板参数吗
#include <stdio.h>
template<int i>
struct Pool
{
static const int stored = i;
};
int main(int argc, char* argv[])
{
printf("%d\n", Pool<5>::stored);
return 0;
}
#包括
模板
结构池
{
存储的静态常数int=i;
};
int main(int argc,char*argv[])
{
printf(“%d\n”,池::已存储);
返回0;
}
部分专门化可以从类型池中解包参数1
,但无法声明引用任何对象并推断类型的模板。函数可以在给定对象的情况下推断类型,但此类对象不能用作非类型模板参数
这里最好的分解可能是将客户机类型嵌套在池类型中
template<int i>
struct Pool{
int id;
// i and the Pool type are already defined at least within this context.
template< Pool & p >
struct C{
int id;
void* operator new(size_t size){
std::cout<<"new";
return malloc(size);
}
void test(){
std::cout << _p.id;
}
};
};
int main() {
FE::pool.id = 120;
Pool<1>::C< FE::pool> c;
c.test();
return 0;
}
模板
结构池{
int-id;
//i和池类型至少已在此上下文中定义。
模板
结构C{
int-id;
void*运算符新(大小\u t大小){
std::couty您的语法无效“我能以某种方式避免第一个参数吗?”不,但也许您可以在更大的范围内简化它。更完整的示例可能会有所帮助。例如,您可以将类型传递给C
,并要求它具有名为pool
的静态数据成员(或静态成员函数)@DyP-你能澄清一下吗?模板结构C{void test(){cout
#include <iostream>
#include <stdlib.h> /* malloc, free, rand */
using namespace std;
template<int i>
struct Pool{
int id;
};
struct FE{
static Pool<1> pool;
};
Pool<1> FE::pool;
template<typename T, T &_p>
struct C{
int id;
void* operator new(size_t size){
std::cout<<"new";
return malloc(size);
}
void test(){
std::cout << _p.id;
}
};
int main() {
FE::pool.id = 120;
C<Pool<1>, FE::pool> c;
c.test();
return 0;
}
#include <stdio.h>
template<int i>
struct Pool
{
static const int stored = i;
};
int main(int argc, char* argv[])
{
printf("%d\n", Pool<5>::stored);
return 0;
}
template<int i>
struct Pool{
int id;
// i and the Pool type are already defined at least within this context.
template< Pool & p >
struct C{
int id;
void* operator new(size_t size){
std::cout<<"new";
return malloc(size);
}
void test(){
std::cout << _p.id;
}
};
};
int main() {
FE::pool.id = 120;
Pool<1>::C< FE::pool> c;
c.test();
return 0;
}