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