程序中写过这样几个函数:
extractUInt
1unsignedintextractUInt(byte*element)
2{
3byteid=0;
4byte*decodedUInt=NULL;
5unsignedshortdecodedUIntLength=ElementHandler::decode(element,&id,&decodedUInt);
6unsignedintui=0;
7memcpy_s(&ui,sizeof(ui),decodedUInt,decodedUIntLength);
8
9delete[]decodedUInt;
10returnui;
11}
extractUShort
1unsignedshortextractUShort(byte*element)
2{
3byteid=0;
4byte*decodedUShort=NULL;
5unsignedshortdecodedUShortLength=ElementHandler::decode(element,&id,&decodedUShort);
6unsignedshortus=0;
7memcpy_s(&us,sizeof(us),decodedUShort,decodedUShortLength);
8
9delete[]decodedUShort;
10returnus;
11}
extractByte
1byteextractByte(byte*element)
2{
3byteid=0;
4byte*decodedByte=NULL;
5unsignedshortdecodedByteLength=ElementHandler::decode(element,&id,&decodedByte);
6byteby=0;
7//memcpy_s(&by,sizeof(by),decodedByte,decodedByteLength);
8by=*decodedByte;
9
10delete[]decodedByte;
11returnby;
12}
写的时候并未觉得异样,昨天再次查看的时候才发现三个函数语义重复,仅返回值不同,于是想到模板函数。想当然地写成了这样:
Code
1template<classT>
2TextractNumber(byte*element)
3{
4byteid=0;
5byte*decoded=NULL;
6unsignedshortdecodedLength=ElementHandler::decode(element,&id,&decoded);
7
8Tt=0;
9memcpy_s(&t,sizeof(t),decoded,decodedLength);
10
11delete[]decoded;
12returnt;
13}
编译时未报错,但在调用时
1unsignedshortus=extractNumber(element);
会出现编译错误,提示无法为“T”推导模板参数。改成如下模样即可解决问题:
1unsignedshortus=extractNumber<unsignedshort>(element);