Search code examples
c++variadic-templatesparameter-pack

How to Store Variadic Template Arguments Passed into Constructor and then Save them for Later Use?


I am curious how one would go about storing a parameter pack passed into a function and storing the values for later use.

For instance:

class Storage {
public:
   template<typename... Args>
   Storage(Args... args) {
     //store args somehow
   }
 }

Basically I am trying to make a class like tuple, but where you don't have to specify what types the tuple will hold, you just pass in the values through the constructor.

So for instance instead of doing something like this:

std::tuple<int, std::string> t = std::make_tuple(5, "s");

You could do this:

Storage storage(5, "s");

And this way you could any Storage objects in the same vector or list. And then in the storage class there would be some method like std::get that would return a given index of an element we passed in.


Solution

  • Since run will return void, I assume all the functions you need to wrap can be functions that return void too. In that case you can do it like this (and let lambda capture do the storing for you):

    #include <iostream>
    #include <functional>
    #include <string>
    #include <utility>
    
    class FnWrapper
    {
    public:
        template<typename fn_t, typename... args_t>
        FnWrapper(fn_t fn, args_t&&... args) :
            m_fn{ [=] { fn(args...); } }
        {
        }
    
        void run()
        {
            m_fn();
        }
    
    private:
        std::function<void()> m_fn;
    };
    
    void foo(const std::string& b)
    {
        std::cout << b;
    }
    
    int main()
    {
        std::string hello{ "Hello World!" };
        FnWrapper wrapper{ foo, hello };
        wrapper.run();
        return 0;
    }