0

If I have a class which has a defined constructor:

class Point
{
public:
    Point(int x, int y);
    // ...
};

And a std::tuple:

using Tuple = std::tuple<int,int>;

I can construct the class using the tuple by calling std::make_from_tuple:

void f()
{
    Tuple tuple = {1,2};
    auto point = std::make_from_tuple<Point>(tuple);
}

If e.g. my class is using only factory methods and has no defined constructor:

class Point
{
    Point() = delete;

public:
    static Point from_coordinates(int x, int y);
    // ...
};

Apparently I cannot customize std::make_from_tuple to use anything else to act as a constructor.

Is there a more generic implementation of std::make_from_tuple available in STL or in Boost? Is it possible to use anything else to achieve the same result?

4
  • 1
    If you look up make_from_tuple on cppreference.com, you will see exactly what it does, and you should be able to simply adapt it to use your factory method. Which is pretty close to what std::apply does. You can probably feed a lambda to std::apply that forwards its arguments to your factory. Nov 20, 2020 at 15:35
  • Is there a reason not to implement Point(Tuple xy); constructor?
    – Eljay
    Nov 20, 2020 at 15:36
  • @Eljay assume class code is from third party and you cannot change it Nov 20, 2020 at 15:44
  • Then you could make a freestanding Point to_Point(Tuple xy); factory function.
    – Eljay
    Nov 20, 2020 at 16:03

1 Answer 1

2

You can use std::apply to call from_coordinates with a std::tuple. That would look like

auto point = std::apply(Point::from_coordinates, tuple);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.