Conditionally choose a type with decltype() and the ternary operator

前端 未结 1 609
闹比i
闹比i 2021-01-15 13:47

I have a file a.cpp:

#include 

using namespace std;

int main(){
    int a=5;
    double b=4.3;
    decltype(a>b?a:b) n;
           


        
相关标签:
1条回答
  • 2021-01-15 14:41

    C++ is a statically-typed language.

    That means, the type of a thing cannot depend on runtime criteria.

    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.

    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).

    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.

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

    0 讨论(0)
提交回复
热议问题