簡體   English   中英

將元組類型轉換為另一種元組類型

[英]Transform tuple type to another tuple type

假設我有一個元組類型std::tuple<x,y,z> ,或者可能std::tuple<a,b> 我想要一種通用的方法來轉換我的元組中的類型,例如“功能化”以獲得

std::tuple<std::function<void(x)>,
           std::function<void(y)>,
           std::function<void(z)>>

或者也許為 shared_pointers 獲取存儲空間,例如

std::tuple<std::shared_pointer<a>,
           std::shared_pointer<b>>

我將如何使用 C++17 實現這一目標? C++20 的答案很有趣,但不適用於我目前的情況。

動機:我有一個 class 將由任意且不一定唯一的類型列表進行參數化,並且希望列表中的每種類型都有一個 std::function 成員。

模板專業化可能是最簡單的方法。

template <typename T>
struct functionize;

template <typename... Ts>
struct functionize<std::tuple<Ts...>> {
    using type = std::tuple<std::function<void(Ts)>...>;
}

using MyTuple = std::tuple<int, double, char>;
using MyTupleFunctionized = typename functionize<MyTuple>::type;

為了使其更通用,您可以接受模板模板參數以應用於包。

template <typename Tuple, template <typename> typename Component>
struct transform_tuple;

template <typename... Ts, template <typename> typename Component>
struct transform_tuple<std::tuple<Ts...>, Component> {
    using type = std::tuple<Component<Ts>...>;
}

using MyTuple = std::tuple<int, double, char>;
using MyTransformedTuple = typename transform_tuple<MyTuple, std::shared_ptr>::type;

更通用的解決方案最適用於c++17或更高版本。 在此之前,它只會匹配具有恰好 1 個參數的模板。 c++17之后,它還可以匹配std::vector之類的東西,它有兩個模板參數,而第二個模板參數有一個默認參數。

編輯:
正如@Jarod42 和@Caleth 在評論中指出的那樣,我們可以在這方面進行更多改進。

template <typename Tuple, template <typename...> typename Component>
struct transform_tuple;

模板模板參數的參數包允許我們從c++11和轉發傳遞類似std::vector的東西。 如果我們想傳遞混合類型和非類型參數的東西,比如std::array ,那只會留下問題。

我們可以通過使用模板別名來部分解決這個問題。

template <typename T>
using FixedArray10 = std::array<T, 10>;

using MyTransformedTuple = typename transform_tuple<MyTuple, FixedArray10>::type;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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