mardi 27 janvier 2015

understanding usage of std::function as parameter [duplicate]


This question already has an answer here:




I want to give a function as parameter to my function using 'std::function'. My function is like below;



template <class T>
bool mySort(T *arr, const int &size, std::function<bool (T, T)> CompareFunction)
{
//something
}


In my main function I create a random assigned integer array and give it to this function with my own compare function.



bool myCompare (int a , int b)
{
return (a < b) ? true : false;
}

int main(int argc, char** argv) {
int a[20];
srand(time(0));
for(int i = 0; i < 20; ++i)
{
a[i] = rand();
}
.....
}


Problem is that, if I use an object as below, it works fine, but if I directly give function it raises an error;



std::function<bool (int, int)> asd = myComp;
mySort(a, 20, asd); //This works just fine
mySort(a, 20, myComp); //This gives 'no matching function' error


I don't understand the reason. Also couldn't find any logical explanation on Internet. Problem also exists for lambda functions;



std::function<bool (int, int)> asdf = [](int a, int b)
{
return (a<b);
};
mySort(a, 20, asdf); //This is fine
mySort(a, 20, [](int a, int b)
{
return (a<b);
}); //This is not


Any ideas or suggestions are welcome.


Aucun commentaire:

Enregistrer un commentaire