【问题标题】:How to infer the type of the function that can return type depending on condition?如何根据条件推断可以返回类型的函数的类型?
【发布时间】:2016-05-02 07:09:36
【问题描述】:

我有一个模板函数,它接受两种数据类型 - int 和 double 并返回较小的那个,现在,我如何推断该函数将返回的类型?现在,我正在丢失小数点后的部分。

#include <iostream>

using namespace std;

template <class First, class Second>
First smaller(First a, Second b){
   return (a < b ? a : b);
}

int main () {
   int x = 100;
   double y = 15.5;
   cout<< smaller (x,y) << endl;

}

【问题讨论】:

  • 您希望返回类型取决于哪个输入更小,还是希望它查看 int 和 double 的输入类型并确定 double 是最佳输出类型? C++ 是静态类型的,因此返回类型不能依赖于输入值。
  • 如果你试图根据输入来决定函数的返回类型,这在 C++ 中是不可能的。

标签: c++ templates c++11 casting


【解决方案1】:

三元运算符的标准行为是执行“通常的算术转换”。在这种情况下,意味着将int 提升为double。 这与auto x=1/1.0; 中的相同是double,因为整数分子与double 分母兼容。

查看What is the type of "auto var = {condition} ? 1 : 1.0" in C++11? Is it double or int? 的答案。 有“外行术语”和标准引用答案。两者都应该有帮助。

但是你所做的是强制类型为“第一”:

template <class First, class Second>
First smaller(First a, Second b){
   return (a < b ? a : b);
}

查看您为smaller 输入的返回类型。 所以发生的事情是它被提升为double,然后转换为int返回值。

看看这个:

#include <iostream>

template <class First, class Second>
First smaller(First a, Second b){
   return (a < b ? a : b);
}


template <class First, class Second>
auto smaller_auto(First a, Second b){
   return (a < b ? a : b);
}


int main() {
    int x=100;
    double y=15.5;

    std::cout<< smaller(x,y)<<std::endl; //First is int returns an int.

    std::cout<< smaller(y,x)<<std::endl;//First is double returns double.


    std::cout<< smaller_auto(x,y)<<std::endl; //Performs the usual arithemtic conversions (returns double).

    std::cout<< smaller_auto(y,x)<<std::endl;//Performs the usual arithemtic conversions (returns double).

    return 0;
}

预期输出:

15
15.5
15.5
15.5

【讨论】:

  • 您已经描述了问题,但没有描述解决方案,即将返回类型声明为std::common_type&lt;First, Second&gt;::type。如您所示,只需使用auto 是一种解决方案,但仅适用于C++ 14,并且此问题标记为c++11
  • @ildjarn 公平点。我还应该指出,“真正的”正确答案是使用std::min&lt;&gt;()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2020-02-28
  • 2020-06-06
  • 1970-01-01
  • 2020-03-23
  • 2021-07-18
  • 1970-01-01
相关资源
最近更新 更多