How to store a variable number of parameters in a class?

Mar 31, 2016 at 5:45pm
Hi,

I have a class that executes a member function in its destructor, to ensure the functionality is performed when abandoning the scope. It can take a parameter of any type (as seen below), but I want to extend it so it can receive any number of parameters and any type of parameters (sounds like a candidate for variadic templates). However how does one store this variable number/type of parameters for use when one invokes the member function?

This is what I have so far (only one parameter supported):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<typename T, typename P, typename Ret = void>
        struct Defer {
            
            using PMF_P = Ret (T::*)(P par);
            
            Defer(  T& t, PMF_P fnobj, P par ) : obj{t},  fn{fnobj}, parameter{par} {}
            
            ~Defer() {
                (obj.*fn)(parameter);
            }
            
        private:
            T& obj;
            PMF_P fn;
            P parameter;
        };


Thanks !!
Juan
Mar 31, 2016 at 6:25pm
Why not simply take an std::function<void()>? The caller can pass a lambda and bind whatever locals it wants.
Mar 31, 2016 at 6:46pm
Yes, you might do that in this particular case ... however in a more general case, where you receive variable number of parameters which you want to use later in a call to a method, how can one store them for later use?

Its really beyond the original question ... a bit more ambitious

Thanks,
Juan
Mar 31, 2016 at 8:39pm
An idea I have, why not use
std::tuple
since that is variadic? Yet, how could one convert the tuple into a parameter list to give the method in its invocation?

Apr 1, 2016 at 3:47am
> how could one convert the tuple into a parameter list to give the method in its invocation?

C++17: std::apply() http://en.cppreference.com/w/cpp/utility/apply

The latest update for the Microsoft implementation should have it:
We’ve implemented every C++ Standard Library feature that's been voted into C++11, C++14, and the C++17-so-far Working Paper N4567 (pre-Jacksonville). https://www.visualstudio.com/en-us/news/vs2015-update2-vs.aspx
Apr 1, 2016 at 6:49am
Damn. I didn't know about that. That's a really nice feature.
Topic archived. No new replies allowed.