Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 558
EmVee Avatar asked Jan 25 '23 08:01

EmVee


1 Answers

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.

like image 180
Nicol Bolas Avatar answered Jan 30 '23 06:01

Nicol Bolas