[英]Variadically templated struct / How boost::variant is implemented
是否有可能達到如下效果
DifferentTypesInOne<string, int, double> variant_obj;
您的variant_obj
具有字符串,整數和雙variant_obj
類型的變量。
我知道這類似於boost::variant
。 我之前曾搜索過有關此問題的信息,但未能找到一個可以解釋該類如何使用可變參數模板存儲所有類型的元素的解釋。 特別是我在問我如何定義一個struct
,該struct
具有所有給定類型的變量和一個成員變量,該變量表示當前哪個是重要的。
謝謝!
大致,
template<class... Ts>
struct variant_storage {};
template<class T, class... Ts>
struct variant_storage<T, Ts...>{
union {
T head;
variant_storage<Ts...> tail;
};
};
template<class... Ts>
struct variant {
int index;
variant_storage<Ts...> storage;
};
如果不需要constexpr
-ness,則可以存儲std::aligned_union_t<0, Ts...>
作為存儲,並使用new放置,這更簡單。
C ++ 11提供了一個模板類型std::aligned_union
,它接受類型列表。 aligned_union::type
是一種類型,具有足夠的存儲空間和對齊方式,可以作為任何給定類型的存儲。
這樣便可以創建數據存儲。 除此之外,您所需要的只是一個整數,該整數指示存儲在其中的值。
template<typename ...Types>
struct variant
{
private:
uint8_t index;
typename std::aligned_union<Types...>::type storage;
};
在storage提供的storage
,可以使用new
放置將各個元素分配給特定類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.