c++constructortuples

How to construct an object from a tuple when it does not have any constructor


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?


Solution

  • 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);