PrashantKumarNirmal
PrashantKumarNirmal

Reputation: 89

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

I have a file 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();   
}

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

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

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

Upvotes: 2

Views: 377

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

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.

Upvotes: 3

Related Questions