片段,同样在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
已包含。这里出了什么问题?
您实际上有
std::tuple_element_t<0, std::tuple<int, char, float>&>
(注意引用),您需要删除特征中的引用(和 cv 限定符):演示