具有if语句的自动函数将不返回值 [英] auto Function with if Statement won't return a value

查看:79
本文介绍了具有if语句的自动函数将不返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个模板和一个 auto 函数,它们比较两个值并返回最小的值.这是我的代码:

I made a template and an auto function that compare 2 values and return the smallest one. This is my code:

#include <iostream>
using namespace std;

// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
    if (NumOne > NumTwo) {
        return NumTwo;
    }
    else {
        return NumOne;
    }
}

int main() {

    int iA = 345;
    float fB = 23.4243;

    cout << PrintSmaller(iA, fB) << endl;
    cout << PrintSmaller(fB, iA) << endl;

    return 0;
}

但是它无法编译,我在VS 2015上收到此错误:错误C3487'int':所有返回表达式都必须推导为同一类型:以前是'float'

But it won't compile, I get this error on VS 2015: Error C3487 'int': all return expressions must deduce to the same type: previously it was 'float'

但是,如果我删除 if 语句并编写函数 PrintSmaller ,则该函数将无法运行问题:

However, if I delete the if statement and write the function PrintSmaller like this it works with no problems :

auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}

有什么区别?为什么第一个代码无法编译?谢谢.

What is the difference ? and why the first code won't compile ? Thank you.

推荐答案

一个函数只能具有一个 return 类型.使用 return 类型推断意味着它将根据解析器看到的 first return 语句中的表达式类型来推断.如果以后的 return 语句未返回相同类型的表达式,则该函数被认为是自相矛盾的,因此格式不正确.

A function can only have a single return type. Using return type deduction means that it will be deduced based on the type of the expression in the first return statement the parser sees. If later return statements do not return expressions of the same type, then the function is considered to be self-contradictory and thus ill-formed.

在第二种情况下,?:根据基于第二和第三子表达式确定的公共类型来确定表达式的类型.这两个子表达式将转换为该通用类型.

In the second case, the ?: determines the type of the expression based on a common type determined based on the second and third sub-expressions. The two sub-expressions will be converted to this common type.

这与 return 类型推断的工作方式不同.如果您打算使用第一种情况,则需要明确地将返回值转换为所需的返回类型.

That's different from how return type deduction works. If you intend for your first case to work, then you need to explicitly convert the returned value to the desired return type.

这篇关于具有if语句的自动函数将不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆