小编Mik*_* .H的帖子

auto if if语句不会返回值

我制作了一个模板和一个自动函数,比较2个值并返回最小值.这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但它不会编译,我在VS 2015上得到这个错误: 错误C3487'int':所有返回表达式必须推导为相同的类型:以前它是'浮动'

但是,如果我删除if语句并像这样编写PrintSmaller函数它没有问题:

auto PrintSmaller(T NumOne, U NumTwo) …
Run Code Online (Sandbox Code Playgroud)

c++

4
推荐指数
1
解决办法
347
查看次数

标签 统计

c++ ×1