【问题标题】:Function returning Int instead of float返回 Int 而不是 float 的函数
【发布时间】:2021-07-19 00:57:33
【问题描述】:

我正在用 C++ 中的函数指针和 lambdas 进行实验,我的函数定义如下 -

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

并且从我的主要功能中,我将其称为如下 -

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

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

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

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

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

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

PS - 我刚刚意识到返回类型是 int 而不是 type1 并且没有想太多就匆忙发布了这个问题。抱歉问了个小问题

【问题讨论】:

  • compareNumber的返回类型。
  • 天哪,这太尴尬了,完全看不到我的眼睛。非常感谢您指出@interjay
  • 您可能希望从 compareNumber 返回 auto 类型,因此无论输入类型如何,它都是正确的类型。

标签: c++ c++11 lambda function-pointers


【解决方案1】:
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, type1 b, type2 function){
return function(a, b);
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 2023-01-24
      相关资源
      最近更新 更多