Home > database >  Trying to pass a function as a parameter using functional library in c but it is not working
Trying to pass a function as a parameter using functional library in c but it is not working

Time:09-27

// I will define all the functions that are involved.

//First is the sort function that i am trying to pass.

void bubbleSort(vector<int> &vector);

//Second is the function that calls the function that is supposed to take a function as a parameter.

int testSorts(vector<int> &vector, ofstream& outfile, string data)
{
    displaySort(vector, outfile, sortName, bubbleSort);
}

//This is the function that is supposed to take a vector, file, and function as parameter.

// When I run this I get the following error. [Error] template argument 1 is invalid

void displaySort(vector<int>& vector, ofstream& outfile, string data, std::function<void 
(vector<int>& vector)> func)
{func(vector);}

//Here is the code I got from stack overflow that works. What I want to know is why mine does not. I did the same thing.

#include <functional>

double Combiner(double a, double b, std::function<double 
(double,double)> func){
  return func(a,b);
}

double Add(double a, double b){
  return a b;
}

double Mult(double a, double b){
  return a*b;
}

int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

CodePudding user response:

Don't do using namespace std; and specify the namespace and it should work:

void displaySort(std::vector<int>& vector, std::ofstream& outfile,
                 std::string data, std::function<void(std::vector<int>&)> func) 
{
    func(vector);
}

If you for some reason want to stick with using namespace std;, add :: before vector in the function spec:

void displaySort(vector<int>& vector, ofstream& outfile,
                 string data, function<void(::vector<int>&)> func)
//                                          ^^
{
    func(vector);
}
  • Related