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

Viewed 200

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.
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
}
Related