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;
}
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.
是的,它绝对可以,实际上它可以在引入if constexpr
之前在 C++11中使用,甚至在常量表达式中的C++11 之前,例如您问题中的那个。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.