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

1

12

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.
Oina answered 14/8, 2022 at 14:33 Comment(3)
Foo takes a single argument and in Foo<Bar>(5,false); you're passing two arguments.Trow
Seems like a good case for a variadic templateReputed
@Reputed You can forward the arguments, but only in the function body. It needs either another function, or some specialization where the arguments can be forwardedAssembled
B
15

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
}
Billi answered 14/8, 2022 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.