1

This is a follow-up to my previous question: C++ - Constructing wrapper class with same syntax as wrapped data

Basically, I'm trying to make a wrapper template around some data, and construct / set the wrapper with the same syntax as the data.

If I use something like a struct, I can achieve that with forwarding the parameters so the syntax can be:

struct SomeStruct{

    int a, b, c;

    SomeStruct(int _a, int _b, int _c) {/*...*/}

};

// ...

WrapperClass<SomeStruct> wrapped_struct1{1,2,3};
WrapperClass<SomeStruct> wrapped_struct2 = {1,2,3};
WrapperClass<SomeStruct> wrapped_struct3( 1,2,3);

The problem is that this only works if I have that constructor defined in the struct. Can I make it work without having to define it?

The wrapper currently looks like this:

template<typename T> class WrapperClass{
public:
    T data;    
    template <typename...Args>
    WrapperClass(Args&&...args) : data(std::forward<Args>(args)...) {}
};
Newline
  • 769
  • 3
  • 12

1 Answers1

1

You can change to list initialization instead. Then

If T is an aggregate type, aggregate initialization is performed.

e.g.

template <typename...Args>
WrapperClass(Args&&...args) : data{std::forward<Args>(args)...} {}
//                                ^                           ^
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thank you! Do I need to / can keep both constructors or is the list-initialization one enough? – Newline Nov 16 '19 at 05:51
  • 1
    @Newline You can't, they can't be overloaded with same signature. You have to select one, note that for some cases effect might be different; e.g. for `std::vector`, `(10, 42)` would construct a `vector` containing 10 elements with value `42`; `{10, 42}` would construct a `vector` containing 2 elements with value `10` and `42`. You might also apply SFINAE or template specialization to perform dispatch. – songyuanyao Nov 16 '19 at 05:57
  • Now it is all good except that copy-constructor and assignment is not working. It gives an error saying "cannot convert ‘WrapperClass’ to ‘int’ in initialization", and points to the list-init function:S. Even if I explicitly define the copy-ctor. – Newline Nov 16 '19 at 08:14
  • @Newline See [Why is template constructor preferred to copy constructor?](https://stackoverflow.com/q/57909923/3309790) – songyuanyao Nov 16 '19 at 08:27
  • Thanks! I'm trying to understand how to do that same thing with variadic templates. How to stop that function from being called when "Args" is "WrapperClass", but don't know how. Maybe I will have to ask another question:) – Newline Nov 16 '19 at 08:57