簡體   English   中英

當元組沒有任何構造函數時如何從元組構造對象

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM