参考
    https://zhuanlan.zhihu.com/p/37306637

    几个例子

    1. int foo(){
    2. return 5;
    3. }
    4. int main()
    5. {
    6. int (*funcPtr1)() = foo;
    7. int (*funcPtr2)() = &foo; // c++会隐式得把foo转换成&foo,所以你无需再加入&
    8. std::cout << funcPtr1() << std::endl;
    9. std::cout << funcPtr2() << std::endl;
    10. }
    1. #include <iostream>
    2. int add(int a, int b){
    3. return a+b;
    4. }
    5. int sub(int a, int b){
    6. return a-b;
    7. }
    8. void func(int e, int d, int(*f)(int a, int b)){ // 这里才是我想说的,
    9. // 传入了一个int型,双参数,返回值为int的函数
    10. std::cout<<f(e,d)<<std::endl;
    11. }
    12. int main()
    13. {
    14. func(2,3,add);
    15. func(2,3,sub);
    16. return 0;
    17. }
    1. #include <iostream>
    2. template <typename T>
    3. bool ascending(T x, T y) {
    4. return x > y;
    5. }
    6. template <typename T>
    7. bool descending(T x, T y) {
    8. return x < y;
    9. }
    10. template<typename T>
    11. void bubblesort(T *a, int n, bool(*cmpfunc)(T, T)){
    12. bool sorted = false;
    13. while(!sorted){
    14. sorted = true;
    15. for (int i=0; i<n-1; i++)
    16. if (cmpfunc(a[i], a[i+1])) {
    17. std::swap(a[i], a[i+1]);
    18. sorted = false;
    19. }
    20. n--;
    21. }
    22. }
    23. int main()
    24. {
    25. int a[8] = {5,2,5,7,1,-3,99,56};
    26. int b[8] = {5,2,5,7,1,-3,99,56};
    27. bubblesort<int>(a, 8, ascending);
    28. for (auto e:a) std::cout << e << " ";
    29. std::cout << std::endl;
    30. bubblesort<int>(b, 8, descending);
    31. for (auto e:b) std::cout << e << " ";
    32. return 0;
    33. }
    34. // -3 1 2 5 5 7 56 99
    35. // 99 56 7 5 5 2 1 -3 [Finished in 0.4s]