函数返回 Int 而不是 float

问题描述

我正在 C++ 中试验函数指针和 lambda,我的函数定义如下 -

class MyClass:
    def __init__(self):
        pass
#    def func_A(self):
#        print('a')
     
    def func_B(self):
        print('a')

从我的主函数中,我按如下方式调用它 -

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);
}

问题在于,如果我只是单独调用函数,则会返回正确的值,但是当使用 lambda 函数函数指针时,由于我无法指出的原因,这些值会被强制转换为 int。 这是我的输出 -

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;
}

我检查了输出输出类型,它确实是一个整数。我已经检查过如下 -

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

上面的代码片段打印 1.
谁能告诉我这里到底发生了什么?.
TIA

PS - 我刚刚意识到返回类型是 std::cout<<std::is_same<int,decltype(compareNumber<float,max))>()<<std::endl; 而不是 int 并且没有多想就匆忙发布了问题。很抱歉问这个微不足道的问题

解决方法

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

这是你的代码,你已经将“int compareNumber”更改为“type1 compareNumber”,因为你不知道你会得到什么类型的变量

template<typename type1,typename type2>
type1 compareNumber(type1 a,b);
}
,

我刚刚注意到,compare 函数的返回类型是 int 而不是 type1。这完全错过了我的眼睛。很抱歉问这个微不足道的问题。