Search code examples
c++templatesvariadic-templates

Data members from variadic typename template and overloading


Similar to question Declare member variables from variadic template parameter, but with an additional question:

Let's say I have 2 (or many) structs:

struct A { int a; };
struct B { int b; };

And I want to make a class holding dynamic arrays of each, AND be able to have a call doing specific processing to one of those types:

struct Manager<A, B>
{
    std::vector<A> as;
    std::vector<B> bs;
    template<typename T> process();
};

Where, if I call process<A> it will loop over all "as", and process<B> loops over all "bs".

Additionally, I provide A, B or any number of structs (distinct from eachother) as variadic template parameters. In other words, doing Manager<A, B> is the expected use, but doing Manager<A, A, B> is not allowed (because of the 2 'A's).

Is this possible (and, if possible, in a way that doesn't create a stupidly high amount of boilerplate code or is unreadeable)?


Solution

  • From what I understand, std::tuple does the job too:

    template <typename... Ts>
    struct Manager
    {
        std::tuple<std::vector<Ts>...> vectors;
    
        template <typename T, typename F>
        void process(F f) {
            for (auto& e : std::get<std::vector<T>>(vectors)) {
                f(e);
            }
        }
    };
    

    Demo