“迭代”到std :: tuple并可以访问所有构造函数

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

我是可变参数模板的新手,在实现此容器类时遇到了困难。我想要的是获取类型列表,然后创建一个包含每种类型的std::tuplestd::vectors。我遇到的具体困难是对此std::tuple进行“迭代”。

我正在阅读this answer,它提到您可以为此使用std::apply。我不确定我是否理解“折叠表达式”的目的。这是我尝试过的:

#include <iostream>
#include <tuple>
#include <vector>

template<typename... Types>
class VecCollection {
public:
    std::tuple<std::vector<Types>...> m_stuff; // inside or outside?
    VecCollection(unsigned vec_length, Types... things) 
        : m_stuff(std::make_tuple(std::vector<Types>(things)...)) 
    {
        std::apply(
            [](auto&&... vecs) { 
                for(int i = 0; i < 3; ++i) {
                    vecs.push_back(Types()...);
                }
            }, 
            m_stuff);
    }
};



int main() {
    VecCollection<int, float>(3, 2.6, 400);
    return 0;
}

如果删除构造函数内部的apply调用,它将进行编译。我认为问题是Types()...。我可以以一般方式访问每个构造函数吗?

如果我回到运行时多态性并为所有这些Types保留一堆指向基类的指针,会容易吗?

c++ c++17 variadic-templates stdtuple parameter-pack
1个回答
0
投票

尝试一下。

template<typename... Types>
class VecCollection {
public:
    std::tuple<std::vector<Types>...> m_stuff; // inside or outside?

    VecCollection(unsigned vec_length, Types... things)
        : m_stuff(std::make_tuple(std::vector<Types>(things)...))
    {
        std::apply(
            [](auto&&... vecs) {
                for(int i = 0; i < 3; ++i) {
                    ((vecs.push_back(Types()), ...));
                }
            },
            m_stuff);
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.