c++ - 如何在 C++ 中通过多种类型从元组中选择多个元素?
问题描述
这是我的代码,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>();
此模板函数的参数是int
和bool
。
但很明显,您的data
元组包含其中std::vector
的 s,因此您的select()
方法应该是:
template <class... As>
auto select() {
return std::make_tuple(std::get<std::vector<As>>(data)...);
}
推荐阅读
- r - 如何在 R 中解析堆叠的嵌套 JSON 文件?
- php - 查询 MySQL 数据库
- list - 无法识别列表中的所有元素
- node.js - 通过 Node.js 将以下文本行转换为合格的数组对象?
- react-native - React Native StackNavigator:将道具从屏幕传递到下一个屏幕的标题
- c++ - 如何修复此 sfml 头文件命名空间错误?
- python - 在 python 中使用 nurbs / geomdl 在 3D b 样条上查找点的曲率中心
- date - SQL Developer 定义日期
- javascript - json-rules-engine 处理对象数组
- go - 在 Visual Studio 代码中调试 cgo 会产生“多重定义”错误