在C++中,如何通过几种类型从元组中选择多个元素

how select multiple elements from a tuple by several types in C++?

本文关键字:元组 选择 类型 元素 几种 C++ 何通过      更新时间:2023-10-16

这是我的代码,a应该得到一个类型为std::tuple<int,bool>的变量。但是,它不起作用。那么,哪里出了问题,如何解决呢?

#include <vector>
#include <tuple>
template <class... Ts>
class vector_df {
public:
std::tuple<std::vector<Ts>...> data;
template <class... As>
auto select() {
return std::make_tuple(std::get<As>(data)...);
}
};
int main() {
vector_df<int,char,bool> df;
auto a = df.select<int,bool>();
return 0;
}

这是一个在线C++IDE上的代码链接。https://godbolt.org/z/BwzvCZ错误消息:

/opt/compiler-explorer/gcc-9.1.0/include/c++/9.1.0/tuple: In instantiation of 'constexpr _Tp& std::get(std::tuple<_Elements ...>&) [with _Tp = int; _Types = {std::vector<int, std::allocator<int> >, std::vector<char, std::allocator<char> >, std::vector<bool, std::allocator<bool> >}]':
<source>:11:38:   required from 'auto vector_df<Ts>::select() [with As = {int, bool}; Ts = {int, char, bool}]'
<source>:17:34:   required from here
/opt/compiler-explorer/gcc-9.1.0/include/c++/9.1.0/tuple:1365:37: error: no matching function for call to '__get_helper2<int>(std::tuple<std::vector<int, std::allocator<int> >, std::vector<char, std::allocator<char> >, std::vector<bool, std::allocator<bool> > >&)'
1365 |     { return std::__get_helper2<_Tp>(__t); }
|              ~~~~~~~~~~~~~~~~~~~~~~~^~~~~

auto a = df.select<int,bool>();

此模板函数的参数为intbool

但很明显,您的data元组包含其中的std::vectors,因此您的select()方法应该是:

template <class... As>
auto select() {
return std::make_tuple(std::get<std::vector<As>>(data)...);
}