【发布时间】: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