1

I want to write a wrapper function to which I can pass constructor initialization parameters for some class object. This wrapper will then use this list and pass on to constructor while defining a new object of that class. Not sure what STL or any other data type to use for this purpose. Basically in below code what data type should be used for argument_list. Any library which can assist?

Some code for perspective

class abc{
    int a_;
    char b_;
    public:
    abc(int a, char b)
        :a_(a), b_(b)
    {
    }
}
// Wrapper
template <typename T>
void create_object_wrapper(argument_list list) // assuming argument_list can                              
                                       //hold the parameters as
                                       //intended
{
     abc v1(list); //The use case I want
}      

int main()
{
 create_object_wrapper(1,'a'); // initialize object with (1, 'a')
 return 0;
}

Thanks in advance.

bdubey
  • 307
  • 4
  • 13

3 Answers3

4

use variadic perfect forwarding:

template <typename... Args>
void create_object_wrapper(Args&&... list)
{
     abc v1(std::forward<Args>(list)...);
}  
sehe
  • 374,641
  • 47
  • 450
  • 633
1

Use template parameter packs:

template <typename... Args>
void create_object_wrapper(Args... list)
{
     abc v1(list...);
}  

This will fail to compile if called with arguments which result in an invalid abc constructor call.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

If you want to create the object instantly from the arguments provided, then follows sehe's answer.

If you want to store the arguments provided to create one or more objects later, then you should use a std::tupel. Follow the answers given in this question to see how this can be done. Ideally you want to use C++14 for that (see my answer to that question).

Community
  • 1
  • 1
Walter
  • 44,150
  • 20
  • 113
  • 196