您的位置:首页 > 其它

一次小小的模板尝试

2013-04-22 09:54 155 查看
近日,项目中追加了一个需求,打印log。

要求:在函数的异常退出处打印一些有用的参数。如函数的传入参数,异常返回值等等。一次最多可以打印5个参数。当参数多余两个的时候打印两行

如图,输出参数最多可以有五个,当大于2个时输出两行,当参数小于和等于2个时,输出一行。

遇到的问题:

1,输出log时需要确定要输出的参数个数。

2,参数的类型有多种。

项目中已经有人写了一份log函数,但是实现的有点生硬,大致代码如下:

#include <iostream>
#include <cstring>

typedef unsigned char	U1;
typedef unsigned short	U2;
typedef unsigned long	U4;
typedef char		I1;
typedef short		I2;
typedef long		I4;
typedef void		VD;

class log {
private:
log(){
memset(au1Buffer, 0, sizeof au1Buffer);
}
U1 au1Buffer[32];
public:
~log(){}
VD InitLogBuffer(U1 u1ModelID) {
au1Buffer[3] = u1ModelID;
}

VD StartLog(U1 u1FunctionID, U1 u1FlagID) {
au1Buffer[4] = u1FunctionID;
au1Buffer[5] = u1FlagID;
}

VD SetFirstParam(VD* ptr, U4 BufferSize) {
// code
}

VD SetSecondParam(VD* ptr, U4 BufferSize) {
// code
}

VD SetThreeParam(VD* ptr, U4 BufferSize) {
// code
}

VD SetFourParam(VD* ptr, U4 BufferSize) {
// code
}

VD SetFiveParam(VD* ptr, U4 BufferSize) {
// code
}

void EndLog() {
//print log
}
};


这样实现,每次要输出log时必须先调用StartLog,然后输入各个参数,最后在调用EndLog来把log输出出去。每次至少要三部才能完成输出log的作用。

分析一下:为什么StartLog和EndLog需要成对使用呢,因为不能事先知道有多少个参数要输出,那我可不可以通过参数个数来减去这两步的繁琐呢。我认为可以。

接写来遇到的另一个问题,每次输入的参数类型不一样,U1,U2,U4,I1等等。这也好说,用template嘛,它不就是做这些事情的么。

于是乎着手改写log输出的实现,改写后如下。

class temlog {
private:
temlog(){}
temlog(temlog & rhs);
U1 au1Buffer[32];
public:
~temlog(){}
VD InitBuffer(U1 ModelID, U1 FunctionID, U1 FlagID)
{}

template <class Param1>
VD SetParams(Param1)
{}

template <class Param1, class Param2>
VD SetParams(Param1, Param2)
{}

template <class Param1, class Param2, class Param3>
VD SetParams(Param1, Param2, Param3)
{}

template <class Param1, class Param2, class Param3, class Param4>
VD SetParams(Param1, Param2, Param3, Param4)
{}

template <class Param1, class Param2, class Param3, class Param4, class Param5>
VD SetParams(Param1, Param2, Param3, Param4, Param5)
{}
};

完!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: