打印菱形,C++模板元版
代码:
template<int x>
struct Abs
{
enum {value = x>0?x:-x};
};
#pragma pack(push , 1 )
template<int num ,int x ,int y>//x行数这是多少行,y递归用第几个元素
struct line
{
char mc;
struct line<num,x , y -1> nextLine;
enum { e = Abs<x-num>::value+Abs<y-num>::value<num?'*':' ' };
line():mc(e)
{}
};
template<int num , int x>
struct line<num,x,0>
{
char mc;
char end;
enum { e = Abs<x-num>::value+Abs<0-num>::value<num?'*':' ' };
line():mc(e),end('\n')
{}
};
template<int num, int x , int y>//x行数,不变,y递归用
struct Row
{
line<num,y,x > mc;
Row<num,x , y - 1> nextRow;
};
template<int num , int x>
struct Row<num,x , 0>
{
line<num,0,x> mc;
char end;
Row():end(0){}
};
template<int x>
struct test
{
Row<x , x*2-1,x*2-1> data;
};
#pragma pack(pop )
int main(int argc, char* argv[])
{
test<9> t;
printf("%s\n", &t );
return 0;
}
struct Abs
{
enum {value = x>0?x:-x};
};
#pragma pack(push , 1 )
template<int num ,int x ,int y>//x行数这是多少行,y递归用第几个元素
struct line
{
char mc;
struct line<num,x , y -1> nextLine;
enum { e = Abs<x-num>::value+Abs<y-num>::value<num?'*':' ' };
line():mc(e)
{}
};
template<int num , int x>
struct line<num,x,0>
{
char mc;
char end;
enum { e = Abs<x-num>::value+Abs<0-num>::value<num?'*':' ' };
line():mc(e),end('\n')
{}
};
template<int num, int x , int y>//x行数,不变,y递归用
struct Row
{
line<num,y,x > mc;
Row<num,x , y - 1> nextRow;
};
template<int num , int x>
struct Row<num,x , 0>
{
line<num,0,x> mc;
char end;
Row():end(0){}
};
template<int x>
struct test
{
Row<x , x*2-1,x*2-1> data;
};
#pragma pack(pop )
int main(int argc, char* argv[])
{
test<9> t;
printf("%s\n", &t );
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/akirya/archive/2007/01/18/1486438.aspx