C ++:使用可变参数模板的类包装器

问题描述 投票:0回答:1

我想为其他类obj做一个包装。当包装obj初始化时,我希望能够将我想传递给内部obj的参数传递给它的构造函数:

template <class U, class... Args> struct T {
    T(Args... args) {
        data = new U(args...);
    }
    U* data;
};

我做了一个假人Obj

struct Obj {
    Obj(int a, int b) {
        this->a = a;
        this->b = b;
    }
    int a;
    int b;
};

现在而不是使用Obj obj(1, 2)对其进行初始化,我想使用包装器,因为我会进行一些计算和管理。所以我想要实现的是:

T<Obj> obj(1, 2); // doesn't work, this is what I want to achieve
T<Obj, int, int> obj(1, 2); // works, but it's not what I want it to look like
c++ oop templates wrapper variadic
1个回答
1
投票

class... Args应该是构造函数的模板参数,而不是整个类的模板参数。另外,即使struct Obj无关紧要,您也应该在这里使用完美转发

template <class U>
struct T
{
    template <class ...Args>
    T(Args &&... args)
    {
        data = new U(std::forward<Args>(args)...);
    }
    U *data;
};
© www.soinside.com 2019 - 2024. All rights reserved.