C++ - Constructing wrapper class with same syntax as wrapped data

我怕爱的太早我们不能终老 提交于 2020-01-24 12:32:57

问题


I'm making a template class that is a wrapper around some type of data. I would like to be able to set / construct this class the same way as I set that data when it's not wrapped.

Here's the basic idea:

template<typename T> class WrapperClass{

public:
    T data;

    WrapperClass(const T& _data) : data( _data) {}

    // others stuff

};

Now with something like an integer, I can do this:

WrapperClass<int> wrapped_data = 1;

But with a struct or class I don't know how:

struct SomeStruct{

    int a, b, c;

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

};

//Would like to set the wrapped struct the same way as normal struct:
SomeStruct some_struct1 = { 1,2,3};
SomeStruct some_struct2( 1,2,3);

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

Is there a way to somehow forward the parameters so I can do that latter syntax without an error?


回答1:


The problem with your wrapper is that it requires an already constructed T. Instead you can use a variadic constructor to accept the parameters needed to construct a T:

#include <utility>

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

struct SomeStruct{    
    int a, b, c;    
    SomeStruct(int _a, int _b, int _c) : a(_a),b(_b),c(_c) {}   
};

int main() {
    WrapperClass<SomeStruct> wrapped_struct2{1,2,3};  // ok
    WrapperClass<SomeStruct> wrapped_struct3 = {1,2,3};  // ok
}


来源:https://stackoverflow.com/questions/58882466/c-constructing-wrapper-class-with-same-syntax-as-wrapped-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!