[英]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.