Search code examples
c++visual-studio-2010function-template

function template as a function argument


I want to implement a function which acts as MATLAB sort(). I defined a structure and a function template in a head file, as below.

template<typename T_val> struct SORT_DATA     
{
    T_val value;                     // 
    int index;
};

template<typename T_var> 
bool ccmp(SORT_DATA<T_var> & var_a, SORT_DATA<T_var> & var_b)
{ 
    return var_a.value < var_b.value;
}

In main(), I use a structure variable and pass the ccmp() as an argument to C++ sort(), as below.

//SORT_DATA<double> * data1 = new SORT_DATA<double>[15];
SORT_DATA<double> data1[15];

double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6};

for(int i=0; i<15; i++)
{
    data1[i].value = tmp_data[i];
    data1[i].index = i;
}

//sort(data1, data1+15, ccmp);

for(int i=0; i<15; i++)
    std::cout<<setw(5)<<data1[i].value<<"   ";

std::cout<<std::endl;

for(int i=0; i<15; i++)
    std::cout<<setw(5)<<data1[i].index<<"   ";

I got several problems: 1. It seems that memory was failed to allocate for the structure variable. 2. I got an error message from VS2010 telling that function template cannot be used as a function argument.

#pragma once

#include <iostream>
#include <iomanip>
#include <algorithm>
#include "customizedalg.h"  // This is simply the declaration of the struct and bool cmp().


using namespace std;


int main(int argc, char ** argv)
{

    SORT_DATA<double> * data1 = new SORT_DATA<double>[15];
    //SORT_DATA<double> data1[15];

    double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6};

    for(int i=0; i<15; i++)
    {
        data1[i].value = tmp_data[i];
        data1[i].index = i;
    }

    sort(data1, data1+15, ccmp<double>);

    for(int i=0; i<15; i++)
        std::cout<<setw(5)<<data1[i].value<<"   ";

    std::cout<<std::endl;

    for(int i=0; i<15; i++)
        std::cout<<setw(5)<<data1[i].index<<"   ";

    std::cout<<std::endl;

    std::cin.ignore();

    return 0;
}

Solution

  • You should specify template of ccmp function, as Piotr commented, but you do not need to take address of function:

    std::sort(data1, data1+15, ccmp<double>);

    Here is working sample

    And if your compiler fails to use templated function, you can try making a struct with overloaded operator():

    template<typename T_var> 
    struct ccmp
    {
        bool operator()(SORT_DATA<T_var> & var_a, SORT_DATA<T_var> & var_b) const
        { 
            return var_a.value < var_b.value;
        }
    };
    ...
    std::sort(data1, data1+15, ccmp<double>());
    

    Sample