C++ 模板类型构造函数参数
给定一个模板类:C++ 模板类型构造函数参数,c++,templates,C++,Templates,给定一个模板类: template<class T> class Foo { public: void FunctionThatCreatesT() { _object = new T; } private: shared_ptr<T> _object; } 模板 福班 { 公众: void函数thatCreateSt() { _对象=新T; } 私人: 共享的ptr对象; } 是否可以通过某种方式将T的一组构造函数参数
template<class T>
class Foo
{
public:
void FunctionThatCreatesT()
{
_object = new T;
}
private:
shared_ptr<T> _object;
}
模板
福班
{
公众:
void函数thatCreateSt()
{
_对象=新T;
}
私人:
共享的ptr对象;
}
是否可以通过某种方式将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;
}
#包括
#包括
模板
福班
{
公众:
模板
void函数thatCreateST(Args&&…Args)
{
_object=newt(std::forward)
您可以在C++03中使用许多重载函数来模拟此功能的有限版本,但是..它是一个PITA
此外,这只是从内存中获取的,因此没有进行任何测试。可能包含一个off by one错误