【问题标题】:C++: class wrapper using variadic templatesC++:使用可变参数模板的类包装器
【发布时间】:2020-07-31 21:16:18
【问题描述】:

我想为其他类 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】:

    class... Args 应该是构造函数的模板参数,而不是整个类的模板参数。此外,您应该在此处使用完美转发,即使struct Obj 并不重要。

    template <class U>
    struct T
    {
        template <class ...Args>
        T(Args &&... args)
        {
            data = new U(std::forward<Args>(args)...);
        }
        U *data;
    };
    

    【讨论】:

    • 谢谢。当倒计时允许我选择答案时,我会选择正确的答案
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2019-12-20
    • 2021-10-01
    • 2014-10-02
    相关资源
    最近更新 更多