0

I am new to variadic templates, and I'm having a difficult time implementing this container class. What I want is to take a list of types, and then create a std::tuple that holds std::vectors of each type. The specific difficulty I was having is "iterating" over this std::tuple.

I was reading this answer, and it mentions that you can use std::apply for this. I'm not sure if I understand the purpose of a "fold expression." Here's what I tried:

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

It compiles if I remove the apply call inside the constructor. I think the problem is Types().... Do I have access to each constructor in a general way?

Would it be easier if I just went back to run-time polymorphism and held onto a bunch of pointers to a base class for all these Types?

Taylor
  • 1,797
  • 4
  • 26
  • 51
  • 1
    In which of the vectors do you want to push the values? The one that matches the argument type? – walnut Jan 25 '20 at 21:40
  • @walnut I want to push say ten values in each vector. Same behavior for each element of the tuple – Taylor Jan 25 '20 at 21:42
  • 1
    I don't understand the meaning of the constructor parameters. What is supposed to happen with `3`, `2.6` and `400`? – walnut Jan 25 '20 at 21:45

1 Answers1

1

try this.

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);
    }
};
kusstas
  • 111
  • 3
  • 2
    That does not make sense though with the constructor argument in the use example being a floating point value. OP really must explain what they want the constructor call to do. – walnut Jan 25 '20 at 22:11
  • 1
    It would be helpful to explain _why_ to try this. – Barry Jan 25 '20 at 22:34