Get variadic parameters saved from a cache

84 Views Asked by At

I want to save variable parameters in a cache in one method and use them later in another function. Want to achieve this without making the class 'X' a template class as that would mean I need to propagate the change in the way object can be created to a lot of chained methods. Also if X is templatized then object of X will become different type and can't be saved in same container.

My preferred approach involves making 'bar' a template method. so only relevant callers need to change.

I attempted two approaches, One using 'Ctx' class which I can't make a member as the MsgType is not known at class level. Another approach was using std::vector of variant. How to push paramter to a vector at run time? Any other approach possible?


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

template< typename ...MsgType>
struct Ctx {
    void update(MsgType&& ... items) {
        cache = std::make_tuple(std::forward<MsgType>(items)...);
    }
    std::tuple<MsgType...> cache;
};

struct  X {
    template<typename ...MsgType>
    void bar(const int& y, MsgType&&... args) {
        Ctx<T...> ctx;   
        ctx.update(std::forward<MsgType>(args)...);
        //(vv.push_back(args)...);
    }

    void foo() {
        //use 'args' saved from last call to 'bar' 
    }

    //Ctx<...>
    //std::vector<std::variant<uint16_t, uint8_t, uint32_t>> vv;
};



int main() {

    X x;  //want to avoid making the class 'X' a  template class
    x.bar(1, 10.09, 2121);
    x.bar(2, 10.229, 2334); //Params to all call of bar for one instance of 'X' will have same number & type of args 
    x.foo();

}
0

There are 0 best solutions below