接受类对象的模板函数可以使用其构造函数参数实例化该对象吗?

Ome*_*waz 12 c++ initializer-list implicit-conversion

假设我有一个采用类对象的模板函数:

template<class T>
void Foo(T obj);
Run Code Online (Sandbox Code Playgroud)

和一个类定义如下:

class Bar 
{
public:
    Bar(int a, bool b): _a(a), _b(b) {}
private:
    int _a;
    bool _b;
};
Run Code Online (Sandbox Code Playgroud)

有没有办法让下面的代码编译?

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

Dan*_*ani 15

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

在你的情况下,它将是:

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