首页 > 解决方案 > 如何在 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); }

      |              ~~~~~~~~~~~~~~~~~~~~~~~^~~~~


标签: c++templatesvariadic-templatesstdtuple

解决方案


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

此模板函数的参数是intbool

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

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

推荐阅读