您的位置:首页 > 编程语言 > C语言/C++

如何在C++中实现Deprecated API

2004-07-17 16:01 411 查看

如何在C++中实现Deprecated API

How to deprecate an Api in C++

也许开发过程中第一次定义的某一接口是这样的:

1|

2| #pragma once

3| int SomeApiV1(char* byPtr);

4|

测试程序如下:

5| int main()

6| {

7| int value;

8| int ret = SomeApiV1 ((char*)&value);

9| printf("Value Return is %d, Param return is %#06x", ret, value);

10| return 0;

11| }

12|

过了一段时间后,该函数的第二版定义成这样,第一版已经不用了.

13| #pragma once

14|

15| int SomeApiV1(char* byPtr); //Deprecated

16| int SomeApiV2(int& byRef);

17|

实际上SomeApiV1已经成为SomeApiV2的包装.

18| int SomeApiV1(char* byPtr)

19| {

20| int value;

21| int ret = SomeApiV2(value);

22| memcpy(byPtr, &value, sizeof(int));

23| return ret;

24| }

25|

这时测试程序完全可以自然的编译通过.

如果测试程序的作者不查看头文件中的注释,完全不知道,接口已经被放弃.而可能一直使用旧接口.

如果接口改为:

26| #pragma once

27| int SomeApiV2(int& byRef);

28|

29| template <int IS_DEPRECATED>

30| int SomeApiV1(char* byPtr);

31|

32| //

33| // Deprecated Api wrap here

34| //

35| template <>

36| int SomeApiV1<DEPRECATED>(char* byPtr)

37| {

38| int value;

39| int ret = SomeApiV2(value);

40| memcpy(byPtr, &value, sizeof(int));

41| return ret;

42| }

43|

这时再编译测试程序,编译器会提示:

error C2783: “int SomeApiV1(char *)” : 未能推导出“IS_DEPRECATED” 的模板参数

DeprecatedApi.cpp(22) : 参见“SomeApiV1”的声明

“参见“SomeApiV1”的声明”!! OK,这就是我们所要的:提示程序作者接口已经放弃.

当然如果暂时还想使用旧版本,也没有关系.在代码中明确说明使用的是已放弃的接口.

即可:

44| int main()

45| {

46| int value;

47| int ret = SomeApiV1<DEPRECATED>((char*)&value);

48| printf("Value Return is %d, Param return is %#06x", ret, value);

49| return 0;

50| }

51|

附SomeApiV1实现:

52| int SomeApiV1(char* byPtr)

53| {

54| byPtr[0] = 0x00;

55| byPtr[1] = 0x01;

56| byPtr[2] = 0x00;

57| byPtr[3] = 0x00;

58|

59| printf("SomeApiV1 called!/n");

60| return 1;

61| }

62|

SomeApiV2实现:

63| int SomeApiV2(int& byRef)

64| {

65| byRef = 0x0200;

66| printf("SomeApiV2 called!/n");

67| return 2;

68| }

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