100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 模板参数仅作为函数的返回值

模板参数仅作为函数的返回值

时间:2020-04-22 19:14:08

相关推荐

模板参数仅作为函数的返回值

程序中写过这样几个函数:

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);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。