dimanche 25 avril 2021

Function returning Int instead of float

I am experimenting with function pointers and lambdas in C++ and my function definitions are as follows -

float max(float a, float b){
    std::cout<<"In float max"<<std::endl;
    return (a > b) ? a : b;
}

int max(int a, int b){
    std::cout<<"In Int max"<<std::endl;
    return (a > b) ? a : b;
}

template<typename type1, typename type2>
int compareNumber(type1 a, type1 b, type2 function){
    return function(a, b);
}

and from my main function, I am calling it as follows -

int main(){

    std::cout<<compareNumber<float, float (float, float )>(5.2542f, 2.314f, max)<<std::endl;
    std::cout<<compareNumber<float>(1.3467f, 2.6721f, [=](float a, float b){
        return (a > b) ? a:b;
    })<<std::endl;

    std::cout<<max(5.3f, 2.7f)<<std::endl;
    std::cout<<max(1, 2)<<std::endl;
}

The Issue is that, If I simply invoke the function separately, the correct values get returned, but when using a lambda function or a function pointer, the values get cast to int for reasons I am not able to point out.
Here Is my output -

In float max
5
2
In float max
5.3
In Int max
2

I checked the output type of the output and it indeed is an integer. I had checked it as follows -

std::cout<<std::is_same<int, decltype(compareNumber<float, float (float, float )>(5.2542f, 2.314f, max))>()<<std::endl;

The above code snippet prints 1.
Could anyone please tell me as to what exactly is happening here?.
TIA

PS - I just realized that the return type is int and not type1 and had posted the question without thinking much and in a hurry. Sorry for the trivial question

Aucun commentaire:

Enregistrer un commentaire