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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With