C++,未定义模板 std::tuple_element 的隐式实例化

问题描述 投票:0回答:1

片段,也在 godbolt

#include <tuple>
#include <utility>

template <typename Tuple, std::size_t... Ints>
auto select_tuple(Tuple&& tuple, std::index_sequence<Ints...>) {
    return std::tuple<std::tuple_element_t<Ints, Tuple>...>(
        std::get<Ints>(std::forward<Tuple>(tuple))...);
}

int main() {
    std::tuple<int, char, float> t{1, 'x', 2.0};
    auto t2 = select_tuple(t, std::index_sequence<0, 2>{});
}

正如您在 godbolt 链接中看到的,编译器抛出错误:

/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/15.0.0/../../../../include/c++/15.0.0/bits/utility.h:135:5: error: implicit instantiation of undefined template 'std::tuple_element<0, std::tuple<int, char, float> &>'
  135 |     using tuple_element_t = typename tuple_element<__i, _Tp>::type;

编译器认为它不知道

std::tuple_element
,但
tuple
包含在内。 这里出了什么问题?

c++ compiler-errors tuples
1个回答
0
投票

您需要删除特征中的引用:

template <typename Tuple, std::size_t... Ints>
auto select_tuple(Tuple&& tuple, std::index_sequence<Ints...>) {
    return std::tuple<std::tuple_element_t<Ints, std::remove_reference_t<Tuple>>...>(
        std::get<Ints>(std::forward<Tuple>(tuple))...);
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.