首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问这样一个模板怎样实现?

2012-03-15 
请教这样一个模板怎样实现??有这样一个需求,请问怎么实现:templareuint32ITEM_CNT,uint32ITEM_SIZEclass

请教这样一个模板怎样实现??
有这样一个需求,请问怎么实现:


templare   <uint32   ITEM_CNT,   uint32   ITEM_SIZE>
class   something
{
Tm_map[ITEM_CNT];
charm_buf[ITEM   *   ITEM_SIZE];
};

其中希望根据   ITEM_CNT   的大小自动定义出   T   的类型,就像如此写(当然下面的写法通不过编译)

templare   <uint32   ITEM_CNT,   uint32   ITEM_SIZE>
class   something
{
#if   ITEM_CNT   <   256
typedef   uint8   T;
#else   ITEM_CNT   <   65535
typedef   uint16   T;
#else
typedef   uint32   T;
#endif

Tm_map[ITEM_CNT];
charm_buf[ITEM   *   ITEM_SIZE];
};

或者假如可能
templare   <uint32   ITEM_CNT,   uint32   ITEM_SIZE,   class   T   =   othertemp <ITEM_CNT> >
class   something
{
Tm_map[ITEM_CNT];
charm_buf[ITEM   *   ITEM_SIZE];
};

其中如下能转换出   T   的类型
template   <uint32   LEN>
class   othertemp
{
...
};

以上目的是想做一个   mem_pool,对于   T   的类型长度定义不同,能节省一定的   map   占用的空间

请指点,谢谢!


[解决办法]
这样行不行?
template <int x>
struct mytype;

template <>
struct mytype <1>
{
typedef char type;
};
template <>
struct mytype <4>
{
typedef int type;
};
template <int x>
struct test
{
typename mytype <x> ::type val;
};
int main(int,char*[])
{
cout < <typeid(test <1> ().val).name() < <endl;
cout < <typeid(test <4> ().val).name() < <endl;
return 0;
}

[解决办法]
这个是不行的吧感觉违反了模板参数推演的思想了
根据执行时实参的类型获得推演出模板参数类型
这个实参的类型还得判断然后分支推演
[解决办法]
要知道宏在什么时候处理,实例化在什么时候。

[解决办法]
当然是模板特化。
akirya(坏[其实偶不是什么所谓的坏人]) ( )的代码差不多了。
[解决办法]
不是固定的值整除一个256不就行了
[解决办法]
编译器当然可以做几乎任何算术运算。
把1~255的常量转U8,在模板元编程里太小菜了。
template <int x> struct Helper2_
{
typedef int type;
};

template <> struct Helper2_ <0>
{
typedef short type;
};

template <int x> struct Helper_
{
typedef typename Helper2_ <x / 256> ::type type;
};

template <> struct Helper_ <0>
{
typedef char type;
};

template <int x> struct Int2Type
{
typedef typename Helper_ <x / 256> ::type type;
};

int main(void)
{
cout < < typeid(Int2Type <24> ::type).name() < < endl;
cout < < typeid(Int2Type <274> ::type).name() < < endl;
cout < < typeid(Int2Type <2746584> ::type).name() < < endl;
当然,用loki/boost,基本上这个功能是现成的。

热点排行