使用decltype()和三元运算符有条件地选择一种类型 [英] Conditionally choose a type with decltype() and the ternary operator

查看:71
本文介绍了使用decltype()和三元运算符有条件地选择一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 a.cpp

#include <bits/stdc++.h>

using namespace std;

int main(){
    int a=5;
    double b=4.3;
    decltype(a>b?a:b) n;
    cout << typeid(n).name();   
}

以上代码的输出为 d ,但我希望它是 i ,因为 a大于 b

The Output of above Code is d but I expect it to be i as "a" is greater than "b"

我正在尝试了解decltype。

I am trying to learn about decltype. Can you please tell what I am missing here?

我正在使用gcc版本6.3.0(MinGW.org GCC-6.3.0-1)。

I am using gcc version 6.3.0 (MinGW.org GCC-6.3.0-1).

推荐答案

C ++是一种静态类型的语言。

C++ is a statically-typed language.

这意味着,

因此,表达式 a> b?a:b 将始终求值为相同类型的值。这是条件运算符规则的一部分。

For this reason, the expression a>b?a:b will always evaluate to a value of the same type. That's part of the rules of the conditional operator.

在这种情况下,相互兼容的类型(我已经把这个术语补足了)是 double ,因此您将始终获得 double (请参阅规则此处)。

In this case, the "mutually compatible type" (I have made this term up) is double, so you will always get a double (see the rules here).

如果 a 赢得条件,除了 decltype之外,它已从 int 转换为 double code>您的代码是未评估的上下文(因为在运行时,任何内容都不会影响结果),因此甚至不会执行条件,仅计算可能的结果类型,从参数的类型到条件运算符。如果存在多个可能的结果类型,则代码将是模棱两可的,并且您的程序将不可编译。

If a wins the condition, it's converted from int to double, except in decltype your code is an "unevaluated context" (because nothing at runtime can possibly influence the outcome), so the condition isn't even performed, only the possible resulting type is calculated, from the types of the arguments to the conditional operator. If there were multiple possible resulting types, then the code would be ambiguous and your program would not be compilable.

您可以使用 std :: variant ,但请考虑是否真的需要/想要它。

You can get this behaviour with magic like std::variant, but consider whether you really need/want it.

这篇关于使用decltype()和三元运算符有条件地选择一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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