Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have a template function taking a class object:

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

and a class definition as follows:

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.
like image 481
Omer Kawaz Avatar asked Mar 11 '26 17:03

Omer Kawaz


1 Answers

Yes, this can be done with variadic templates and forwarding, and has many standard examples, like 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
}
like image 166
Dani Avatar answered Mar 14 '26 06:03

Dani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!