0

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.

zgrw
  • 127
  • 11
  • 1
    As a fix, you could just take `CompareFunction` as another template type. That'll be more efficient for your lambda example too. – Barry Jan 27 '15 at 12:09
  • Yes I know that, but I really wanted to learn the reason here. The other post you mentioned has the right answer I was looking for. Thank you for your help. – zgrw Jan 27 '15 at 12:12
  • 1
    You need an explicit cast in second case for compiler: `mySort(a, 20, (std::function)myCompare);`, because in first way it is done implicitly in function pointer asignement. – Agnius Vasiliauskas Jan 27 '15 at 13:10

0 Answers0