函数指针实现框架

通过剥离IO,函数指针与enum剥离功能模块,实现框架,最小化修改难度

  1. #include <bitset>
  2. #include <iostream>
  3. #include <limits.h>
  4. #include <queue>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string>
  8. #include <map>
  9. using namespace std;
  10. typedef int (*FP)(int, int);
  11. enum OPRAND_TYPE{END = -1,ADD,SUB};
  12. struct Task{
  13. int op1;
  14. int op2;
  15. OPRAND_TYPE op;
  16. };
  17. int add(int a,int b) {return a+b;}
  18. int sub(int a,int b) { return a-b; }
  19. OPRAND_TYPE getTask(Task &);
  20. void executeTask(const Task);
  21. FP op[2] = {add, sub};
  22. int main(){
  23. Task task;
  24. while (getTask(task)!=END)
  25. {
  26. executeTask(task);
  27. }
  28. }
  29. OPRAND_TYPE getTask(Task &task){
  30. char c;
  31. cin >> c;
  32. switch (c){
  33. case '#':
  34. task.op = END;
  35. break;
  36. case '+':
  37. task.op = ADD;
  38. cin >> task.op1;
  39. cin >> task.op2;
  40. break;
  41. case '-':
  42. task.op = SUB;
  43. cin >> task.op1;
  44. cin >> task.op2;
  45. break;
  46. }
  47. return task.op;
  48. }
  49. void executeTask(const Task task){
  50. cout<<op[task.op](task.op1,task.op2)<<endl;
  51. }

函数指针实现泛型

  1. #include <bitset>
  2. #include <iostream>
  3. #include <limits.h>
  4. #include <queue>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string>
  8. #include <map>
  9. #include <string.h>
  10. using namespace std;
  11. void MySort(void *base, unsigned width,unsigned num,int(*compare)(const void *elem1,const void *elem2)){//这部分意味着我们必须要传入一个compare的函数
  12. char *A = (char*) base;//void* 是不可以进行移动的
  13. char *tmp = (char*)malloc(width);//申请堆空间
  14. for (unsigned i=1;i<num;i++){
  15. for (unsigned j=0;j<num-i;j++)
  16. if (compare(A + j * width,A + (j+1)*width) > 0){//序关系由函数确定
  17. memcpy(tmp,A + j * width,width);//tmp = A[j]
  18. memcpy(A + j * width,A+(j+1)*width,width);//A[j] = A[j+1]
  19. memcpy(A + (j + 1) * width,tmp,width);//A[j + 1] = tmp
  20. }
  21. }
  22. free(tmp);//释放这部分的空间
  23. }
  24. struct TStudent
  25. { char name[20];
  26. int age;
  27. };
  28. TStudent student[] = {{"one",1},{"two",2}};
  29. int num = sizeof(student)/sizeof(student[0]);//计算出来有多少个
  30. int width = sizeof(student[0]);//计算出来宽度
  31. //compare不用给大小,因为compare是调用者给出的,显然不用给出width了
  32. //call back function:在运行中反过来调用
  33. int icompare(const void *elem1, const void *elem2){
  34. TStudent *p1 = (TStudent *)elem1;
  35. TStudent *p2 = (TStudent *)elem2;
  36. return p1->age - p2->age;
  37. }
  38. int scompare(const void *elem1, const void *elem2){
  39. TStudent *p1 = (TStudent *)elem1;
  40. TStudent *p2 = (TStudent *)elem2;
  41. return strcmp(p1->name, p2->name);
  42. }
  43. int main(){
  44. MySort(student, width, num, icompare);
  45. MySort(student, width, num, scompare);
  46. }