模板类型构造函数参数

Template type constructor parameters

本文关键字:参数 构造函数 类型      更新时间:2023-10-16

给定模板类:

template<class T>
class Foo
{
public:
    void FunctionThatCreatesT()
    {
        _object = new T;
    }
private:
    shared_ptr<T> _object;
}

是否有可能以某种方式将T的一组构造函数参数传递给Foo(可能是在构造Foo时),以便Foo在创建T时可以使用它们?仅使用c++ 11的解决方案就可以了(例如,变量在表中)。

正是,可变模板和通过std::forward的完美转发。

#include <memory>
#include <utility>
template<class T>
class Foo
{
public:
    template<class... Args>
    void FunctionThatCreatesT(Args&&... args)
    {
        _object = new T(std::forward<Args>(args)...);
    }
private:
    std::shared_ptr<T> _object;
}

有关其工作原理的列表,请参阅这个出色的回答。

您可以在c++ 03中使用许多重载函数模拟此限制版本,但是…

同样,这只是来自内存,所以没有完成测试。