variadic constructor?

Jan 28, 2016 at 9:07pm
Hi,

I have a variadic template factory function that accepts an unknown number of arguments. This is supposed to call a private constructor, but I don't know how to connect the factory to the actor.

Something like this is what I have:

class X : public std::enable_shared_from_this<X> {
int i;
double d;
public:
template<typename...Ts>
static std::shared_ptr<X> create( Ts&&...params) {
/// HERE!! how do I code this???
/// Assume I have to keep this factory's signature
}
private:
// constructor is private:
X(int x, double y) : i{x}, d{y} {}

};

Thanks
Juan
Jan 28, 2016 at 9:11pm
seems as easy as
1
2
3
4
  template<typename...Ts>
  static std::shared_ptr<X> create( Ts&&...params) {
    return std::shared_ptr<X>{new X(params...)};
  }

(or, better, X(std::forward<Ts>(params)...) since you took forwarding refs)
Last edited on Jan 28, 2016 at 9:13pm
Jan 28, 2016 at 9:25pm
Great!! Thank you, beautiful!!!

One doubt: what happens if we ommit the forward?

Thanks again,
Juan
Last edited on Jan 28, 2016 at 9:28pm
Jan 29, 2016 at 3:01am
if you omit the forward, you might be copying where you could have moved.
Topic archived. No new replies allowed.