C++模板参数中三元表达式编译异常:MSVC报错GCC/Clang正常?
Hey there! Let's break down what's going on here.
First off, let's be clear: the issue you're facing is almost certainly a bug in MSVC 2017, not a mistake in your code.
Why is this happening?
According to the C++ standard, the ternary operator ?: should resolve to the common type of its two result operands. In your case, 42 and 24 are both plain ints—there's no ambiguity here, and the expression is completely valid.
Older versions of MSVC (like 2017) had known quirks with type deduction in simple ternary expressions, even when the operands are identical types. Clang and GCC follow the standard correctly here, which is why they compile your code without issues.
Workarounds if you need to stick with MSVC 2017
- Explicitly cast the result to make MSVC's type checker happy:
auto x = static_cast<int>(1 ? 42 : 24); - Since you know the expression simplifies directly to
42, you could just use that value directly (though I get this is just a minimal reproduction case).
Long-term fix
Upgrade to a newer version of MSVC (2019 or later)—this specific type deduction bug was fixed in subsequent compiler updates, and your code will work as expected without any changes.
You don't need to second-guess your code here—it's standards-compliant, and the problem lies with the older MSVC compiler implementation.
内容的提问来源于stack exchange,提问作者vitaut

