การป้องกันทูเพิลอยู่นอกขอบเขตด้วย if constexpr

รหัสต่อไปนี้คอมไพล์ได้ดีกับ 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);
}

ใน Visual Studio เวอร์ชันล่าสุด (/std:c++latest) การคอมไพล์ล้มเหลวโดยมีดัชนี tuple อยู่นอกขอบเขต (std::tuple_element‹18446744073709551613,std::tuple‹>>)

เป็นไปได้ไหมที่จะป้องกันไม่ให้ tuple อยู่นอกขอบเขตด้วย constexpr เช่นนี้


person Petter    schedule 15.12.2017    source แหล่งที่มา


คำตอบ (1)


นี่เป็นข้อผิดพลาด 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...);
}
person Barry    schedule 15.12.2017