[英]How to construct an object from a tuple when it does not have any constructor
如果我有一个定义了构造函数的类:
class Point
{
public:
Point(int x, int y);
// ...
};
还有一个std::tuple
:
using Tuple = std::tuple<int,int>;
我可以通过调用std::make_from_tuple
使用元组构造类:
void f()
{
Tuple tuple = {1,2};
auto point = std::make_from_tuple<Point>(tuple);
}
例如,如果我的类只使用工厂方法并且没有定义的构造函数:
class Point
{
Point() = delete;
public:
static Point from_coordinates(int x, int y);
// ...
};
显然我无法自定义std::make_from_tuple
以使用其他任何东西作为构造函数。
在 STL 或 Boost 中是否有更通用的std::make_from_tuple
实现? 是否可以使用其他任何方法来达到相同的结果?
您可以使用std::apply
通过std::tuple
调用from_coordinates
。 那看起来像
auto point = std::apply(Point::from_coordinates, tuple);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.