使用"if constexpr"防止元组超出范围

Pet*_*ter 4 c++ visual-c++ c++17

以下代码与GCC和Clang编译良好,但在Visual Studio的最新更新中停止工作(/ std:c ++ latest):

#include <tuple>

template<int pos, typename... T>
void check_tuple(T... types) {
    if constexpr (pos <= -1) {
        // nothing
    } else {
        using Type = typename std::tuple_element<pos, std::tuple<T...>>::type;
    }
}

int main() {
    check_tuple<0>(1.0, 1.0);
    check_tuple<-1>(1.0, 1.0);
}
Run Code Online (Sandbox Code Playgroud)

在最新版本的Visual Studio(/ STD:C++最新的),编译失败,元组索引越界(标准:: tuple_element <18446744073709551613,性病::组<>>).

有可能像constexpr那样防止元组超出界限吗?

Bar*_*rry 6

这是一个VS错误(请向Microsoft报告).代码应该按原样运行.


在此之前,您可以诉诸我们以前用于解决此问题的方法:标记调度.

template<int pos, typename... T>
void check_tuple_impl(std::true_type, T... types) {
    // nothing
}

template<int pos, typename... T>
void check_tuple_impl(std::false_type, T... types) {
    using Type = typename std::tuple_element<pos, std::tuple<T...>>::type;
}

template<int pos, typename... T>
void check_tuple(T... types) {
    check_tuple_impl<pos>(std::integral_constant<bool, (pos <= -1)>{}, types...);
}
Run Code Online (Sandbox Code Playgroud)