简体   繁体   中英

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 eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM