采用类对象的模板函数是否可以使用其构造函数参数实例化该对象?

Can a template function taking class object instantiate that object with it's constructors arguments?

本文关键字:对象 构造函数 参数 可以使 实例化 函数 是否      更新时间:2024-09-29

假设我有一个接受类对象的模板函数:

template<class T>
void Foo(T obj);

以及如下的类定义:

class Bar 
{
public:
Bar(int a, bool b): _a(a), _b(b) {}
private:
int _a;
bool _b;
};

有没有办法编译以下代码?

Foo<Bar>(5,false);
Foo<Bar>({5,false}); // i know this works, just wondering if i can remove the brackets somehow.

是的,这可以通过可变模板和转发来完成,并且有许多标准示例,如std::make_unique

在您的情况下,它将是:

template<class T, class ...Args>
void Foo(Args &&...args)
{
T obj { std::forward<Args>(args)... };
// use obj
}