如何在C++中实现Deprecated API
2004-07-17 16:01
656 查看
如何在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|相关文章推荐
- 如何在C++中实现Deprecated API
- c++ 如何实现多态
- C++--如何实现SDI程序使用CSplitterWnd创建的多个视图的动态地显示和关闭视图
- C++--如何实现SDI程序使用CSplitterWnd创建的多个视图的动态地显示和关闭视图
- 如何用c++实现四叉数的数据结构(一)
- C++--如何实现SDI程序使用CSplitterWnd创建的多个视图的动态地显示和关闭视图
- BNF范式 如何用C++实现自动推导
- 如何在C和C++中实现回调
- (vc++ 98版的 xp) C++如何实现ring0
- 如何在C++中实现类似Scanf的变参个数函数
- C++是如何利用虚函数实现多态性的?
- C++ 接口与实现分离技术---如何将文件间的编译关系降至最低
- C++如何实现驱动目录浏览呢
- C/C++面试之算法系列--如何实现用更少的空间表示英文字母(a ~ z)构成char A[n]字符串
- 在选举中,如果不止一个人得票最多,而想要先达到最多票数的人当选,用C/C++如何实现?
- 抱歉,没分了!!!请教linux下,用C/C++编程,如何知道我要实现某一功能需要用到什么函数
- C++中的property库的设计与实现过程(二)——如何为属性指定get_和set_函数?
- C++中如何实现多线程——为汪哥提供
- 如何在C++中实现多态性
- 在c++中如何实现非consle类型的计时器