简体   繁体   English

in C++, can template function taking class object instantiate object with it's constructors arguments?

[英]in C++, can template function taking class object instantiate object with it's constructors arguments?

let's say i have a template function taking a class object:假设我有一个模板 function 采用 class object:

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

and a class definition as follows:和 class 定义如下:

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

is there a way to make the following code compile?有没有办法编译下面的代码?

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

Yes, this can be done with variadic templates and forwarding, and has many standard examples, like std::make_unique .是的,这可以通过可变参数模板和转发来完成,并且有许多标准示例,例如std::make_unique

In your case it would be:在您的情况下,它将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM