在我看来,在 MSVC(版本 15.7.3)中评估了另一个 constexpr-if 语句的废弃分支内的 constexpr-if 语句。
考虑以下代码:
#include <tuple>
#include <type_traits>
template <size_t I>
int test() {
if constexpr(I != 0) {
return 0;
}
else { // This branch is discarded, but it seems that the constexpr-if below is still evaulated?
if constexpr(std::is_same_v<int, std::tuple_element_t<I, std::tuple<int>>>) { // some constexpr check that is valid only when I == 0
return 1;
}
else {
return 2;
}
}
}
int main() {
test<1>();
return 0;
}
上面的代码无法在 MSVC 中编译,因为当超出元组的边界std::tuple_element_t
时将导致静态断言失败。I
这表明被丢弃分支中的代码也以某种方式被评估,即使它依赖于模板参数I
。
根据cppreference, constexpr-if 要求“对于所有可能的专业化,被丢弃的语句不能是错误的”,但我很难确定这里是否是这种情况。
GCC 和 Clang 似乎也可以毫无问题地接受此代码(在 Compiler Explorer 上测试)。
C++ 标准是否可以接受编译错误,或者这里的 MSVC 不兼容?
(另外,如果标准不能保证我期望代码执行的操作,是否有另一种方法来完成嵌套的 constexpr-if 语句?)