我如何使用typedef模板

时间:2017-05-05 15:39:19

标签: c++

我想知道我该怎么办?将template<typename T>typedef一起使用?

template <typename T>
typedef bool (*cmp_func)(T i0, T i1); // <- syntax error here

我正在尝试对模板类型的项目进行排序。

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <ctime>

using namespace std;

typedef bool (*cmp_func)(int i0, int i1);


template<typename T>
void print_array(int n, T *x)
{
        cout << "[";
        for (int i = 0; i < n; ++i) {
                cout << setw(3) << x[i];
        }
        cout << " ]\n";
 }

template <typename T>
bool less_than(T i0, T i1) { return i0 < i1; }

template <typename T>
bool greater_than(T i0, T i1) { return i0 > i1; }

template <typename T>
bool is_sorted(int n, T *x, cmp_func cmp)
{
        for (int i = 1; i < n; ++i)
                if ((*cmp)(x[i], x[i-1]))
                        return false;

        return true;
}  

  template <typename T>
void exchange(T* x, int i, int j)
{
        T t = x[i];
        x[i] = x[j];
        x[j] = t;
}


template <typename T>
void insertion_sort(T *x, int l, int r, cmp_func cmp)
{
        for (int i = l+1; i <= r; ++i) {
                for (int j = i; j > l; --j){
                        if ((*cmp)(x[j], x[j-1]))
                                exchange(x, j, j-1);
                    cout << "  ";
                    print_array(r-l+1, x+l);
                }
        }
}

template <typename T>
void insertion_sort2(T *x, int l, int r, cmp_func cmp)
{
        for (int i = r; i > l; --i)
                if ((*cmp)(x[i], x[i-1]))
                        exchange(x, i, i-1);

        for (int i = l+2; i <= r; ++i) {
                int j = i;
                int v = x[i];
                while((*cmp)(v, x[j-1])) {
                        x[j] = x[j-1];
                        --j;
                }
                x[j] = v;

                cout << "  ";
                print_array(r-l+1, x+l);
        }
}

template <typename T>
void fill_random(T n, T *x)
{
        const int M = 100;

        srand(time(0));

        for (int i = 0; i < n; ++i)
                x[i] = rand() % M;
}

int main(int argc, char **argv)
{
        const int N = 10;
        int x[N];
        fill_random(N, x);
        print_array(N, x);

        insertion_sort(x, 0, N-1, &less_than);
        print_array(N, x);

        if (is_sorted(N, x, &less_than))
                cout << "SORTED\n";
        else
                cout << "NOT SORTED\n";

        return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:2)

从C ++ 11开始,您可以使用using关键字:

template <typename T>
using cmp_func = bool (*)(T i0, T i1);

C ++ 03友好的方法是使用struct

template <typename T>
struct cmp_func
{
    typedef bool (*type)(T i0, T i1);
};