简体   繁体   English

函数预期长时返回双倍

[英]Function returning double when expected long

I recently answered another question and in my answer I had the following code. 我最近回答了另一个问题,而我的回答中包含以下代码。

template<typename T, typename ... Ts>
struct are_arithmetic{
    enum {
        value = std::is_arithmetic<T>::value && are_arithmetic<Ts...>::value
    };
};

template<typename T>
struct are_arithmetic<T>{
    enum {
        value = std::is_arithmetic<T>::value
    };
};

template<typename Arg, typename = std::enable_if_t<std::is_arithmetic<Arg>::value>>
Arg max(Arg arg){
    return arg;
}

template<typename Arg, typename Arg1, typename ... Args, typename = typename std::enable_if_t<are_arithmetic<Arg, Arg1, Args...>::value>>
auto max(Arg arg, Arg1 arg1, Args ... args){
    auto max_rest = max(arg1, args...);
    return arg > max_rest ? arg : max_rest;
}

Now, from this code I assumed that max() would return the maximum number from a given list of numbers as well as retaining its type. 现在,从这段代码中,我假设max()将返回给定数字列表中的最大数字并保留其类型。

But when the original poster tried the code: 但是当原始海报尝试代码时:

int main(){
    auto res = max(1.0, 2, 3.0f, 5, 7l);
    std::cout << typeid(res).name() << " "  << typeid(7l).name();
}

He got dl from stdout. 他从标准输出中得到了dl

This shows that the return type of the function isn't what expected at all. 这表明该函数的返回类型根本不是期望的。 Why does the function not return a long ? 为什么函数不返回很long

It seems to me that when the max () function is called as: 在我看来,当max ()函数被调用为:

auto res = max(1.0, 2, 3.0f, 5, 7l);

Then given its signature: 然后给出其签名:

auto max(Arg arg, Arg1 arg1, Args ... args){
    auto max_rest = max(arg1, args...);
    return arg > max_rest ? arg : max_rest;
}

Here, Arg would obviously be a double . 在这里, Arg显然是double

Then return value is a ternary operator: 然后返回值是一个三元运算符:

return 1.0 > max_rest ? 1.0 : max_rest;

It's not important what max_rest winds out to be. max_rest最终变成什么并不重要。 Let's say it's indeed, a long . 可以说,确实很long So you have a ternary operator, with one double expression, and one long expression. 因此,您有一个三元运算符,带有一个double表达式和一个long表达式。

Seems to me that the long expression is going to be type-promoted to a double , so the return auto type is a double . 在我看来, long表达式将被类型提升为double ,因此return auto type是double

The return type of 返回类型

template<typename Arg, typename Arg1, typename ... Args, typename = typename std::enable_if_t<are_arithmetic<Arg, Arg1, Args...>::value>>
auto max(Arg arg, Arg1 arg1, Args ... args){
    auto max_rest = max(arg1, args...);
    return arg > max_rest ? arg : max_rest;
}

doesn't depend of value, but of given type. 不依赖于值,而是给定的类型。 So here it returns the common type of all args. 因此,这里返回所有args的通用类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM