Can the conditional operator ( ? : ) in C++ be compile time?
Asked Answered
F

2

5

Can the ternary (conditional) operator be used as an analogous to constexpr if(), introduced in C++17?

I would like to add some conditionality to member variables initialization in a template. Would the following expression resolve at compile time or runtime? If so, is there any other operator that resolves at compile time such that template specialisation can be avoided?

template<int a>
struct hello {
    constexpr static int n = (a != 0) ? 10 : 20;
}
Fibrilla answered 29/1, 2020 at 17:23 Comment(5)
"such that template specialisation can be avoided" Why do you want to avoid it?Harpp
@Harpp In favor of concisenessFibrilla
You should probably use constexpr instead of const, especially if compile-time evaluation is important to you (although in this case it will most likely not make a difference.)Compensation
If you only pass in compile-time constant expressions, any decent compiler should be able to evaluate it at compile time.Rambort
Try preprocessor #if.Letishaletitia
P
9

It depends on what you mean by "analogous to constexpr if()". if constexpr requires that the condition is a constant expression. It also has certain privileges in template code to discard the branches not taken.

?: does not have that functionality.

However ?: can appear in constant expressions just fine, and it always could. It doesn't make an expression non-constant.

Parfait answered 29/1, 2020 at 17:27 Comment(0)
A
2

Yes, it absolutely can and in fact it could already be used in C++11 before the introduction of if constexpr, and even before C++11 in constant expressions, such as the one in your question.

Age answered 29/1, 2020 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.