gpt4 book ai didi

c++ - 如何断言 constexpr if else 子句永远不会发生?

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:18 25 4
gpt4 key购买 nike

如果条件为真,我想在非 constexpr 时引发编译时错误,例如:

if constexpr(condition1){
...
} else if constexpr (condition2) {
....
} else if constexpr (condition3) {
....
} else {
// I want the else clause never taken. But I heard the code below is not allowed
static_assert(false);
}

// I'd rather not repeat the conditions again like this:
static_assert(condition1 || condition2 || condition3);

最佳答案

您必须使丢弃的语句依赖于模板参数

template <class...> constexpr std::false_type always_false{};

if constexpr(condition1){
...
} else if constexpr (condition2) {
....
} else if constexpr (condition3) {
....
} else {
static_assert(always_false<T>);
}

这是因为

[temp.res]/8 - The program is ill-formed, no diagnostic required, if

no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or ...

关于c++ - 如何断言 constexpr if else 子句永远不会发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55002708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com