【问题标题】:"iterating" over a std::tuple and having access to all the constructors在 std::tuple 上“迭代”并可以访问所有构造函数
【发布时间】:2020-01-25 21:37:16
【问题描述】:

我是可变参数模板的新手,我很难实现这个容器类。我想要的是获取一个类型列表,然后创建一个std::tuple,其中包含每种类型的std::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 的基类的指针会更容易吗?

【问题讨论】:

  • 您想在哪个向量中推送值?与参数类型匹配的那个?
  • @walnut 我想在每个向量中输入十个值。元组的每个元素的行为相同
  • 不明白构造函数参数的含义。 32.6400 应该发生什么?

标签: c++ c++17 variadic-templates stdtuple parameter-pack


【解决方案1】:

试试这个。

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);
    }
};

【讨论】:

  • 这没有意义,尽管使用示例中的构造函数参数是浮点值。 OP 真的必须解释他们希望构造函数调用做什么。
  • 解释一下为什么尝试这个会很有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2014-11-10
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
相关资源
最近更新 更多