C++ 如何实现模板函数来创建任意类实例?

C++ 如何实现模板函数来创建任意类实例?,c++,function,constructor,reference,variadic-templates,C++,Function,Constructor,Reference,Variadic Templates,我需要实现一个模板函数,该函数允许我使用任意构造函数创建任意类的实例,该构造函数具有任何可能的参数,这些参数可以是左值和右值的任意组合 假设我有两个类-A和B-如下所示: class A { public: A(){} }; class B { A& a1; // I want to be able to call non-constant methods and modify object const A& a2; // This I need only

我需要实现一个模板函数,该函数允许我使用任意构造函数创建任意类的实例,该构造函数具有任何可能的参数,这些参数可以是左值和右值的任意组合

假设我有两个类-A和B-如下所示:

class A
{
public:

A(){}


};

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a(a_), a2(a2_), i(i_) {}
};
我试图实现下面这样的东西,但它只允许我使用左值(命名对象),我将无法传递临时对象。 添加const关键字部分解决了这个问题,但不允许修改可能需要的对象

template <typename TType, typename ... TArgs>
TType create(TArgs&... args)
{
    return TType(args...);
}
模板
t类型创建(目标和参数)
{
返回TType(args…);
}
我想使用如下“创建”功能:

int main()
{
   A a1;
   A a2;
   //function takes both lvalue and rvalue
   B b = create<B>(a1, a2, 1);
}
intmain()
{
A a1;
A a2;
//函数同时接受左值和右值
B=创建(a1,a2,1);
}
有人能提出一个可能的解决方案吗

有人能提出一个可能的解决方案吗

你只是有一些打字错误。特别是,您不需要通过非
const
引用将所有参数作为
TArgs&
传递给
create()
函数。编译器将匹配已经存在的最佳拟合类型(引用)


请参阅另一个。

正如Alan Stokes在上面所评论的,您可以使用接收左值和右值表达式:

template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}
模板
t类型创建(TArgs&&…args)
{
返回TType(std::forward(args)…);
}

您正在寻找的搜索词是“完美转发”。如果其中一种类型不可复制怎么办?@Alan看起来没有用于类型推断的副本,或者构造函数初始值设定项列表中的
a1(a1)
为什么会起到其他作用?
template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}
template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}