Home > OS >  How to sort object's array with function pointer and template?
How to sort object's array with function pointer and template?

Time:07-16

Here is my test code:

template<typename T>
void sort(Result* n_obj, int n, bool (*cmp)(T d,T f)){
    for(int i = 0; i<n-1; i  ){
        for(int j = i 1; j<n; j  ){
            if((*cmp)(d,f)){
                swap(n_obj[i],n_obj[j]);
            }
        }
    }
}

Here is my problem - I get this output:

In function 'void sort(Result*, int, bool (*)(T, T))':
[Error] 'f' was not declared in this scope

why 'f' was not declared?

Note: don't care about 'swap' function

CodePudding user response:

You can not use the generic function arguments of the function pointer as arguments. That makes no sense. You need to specify them:

template<typename T>
void sort(Result* n_obj, int n, bool (*cmp)(T,T), T d, T f){
    for(int i = 0; i<n-1; i  ){
        for(int j = i 1; j<n; j  ){
            if(cmp(d,f)){
                std::swap(n_obj[i],n_obj[j]);
            }
        }
    }
}

You probably want to do this:

template<typename T>
void sort(Result* n_obj, int n, bool (*cmp)(T,T)){
    for(int i = 0; i<n-1; i  ){
        for(int j = i 1; j<n; j  ){
            if(cmp(n_obj[i], n_obj[j])){
                std::swap(n_obj[i],n_obj[j]);
            }
        }
    }
}

With that being said, think about using std::function and std::array or std::vector instead of C-style syntax, if you want to work with C . There's not really an argument to mix the two distinct languages.

  •  Tags:  
  • c
  • Related