变量模板化结构/如何实现boost :: variant

时间:2016-03-24 23:29:48

标签: c++ templates c++11 boost c++14

是否可以达到如下效果

os.walk()

DifferentTypesInOne<string, int, double> variant_obj; 的变量类型为string,int和double。

我知道这与variant_obj类似。我之前搜索过有关它的问题,但我无法找到解释,这可以解释该类如何使用可变参数模板来存储所有类型的元素。特别是我问我如何定义一个boost::variant,其中包含所有给定类型的变量,一个成员变量表示当前哪个是重要的。

谢谢!

2 个答案:

答案 0 :(得分:2)

粗略地说,

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;
};

这是一幅素描;有关详细信息,请these articles阅读。

如果您不需要constexpr - ness,则可以将std::aligned_union_t<0, Ts...>存储为存储,并使用新的展示位置,这更简单。

答案 1 :(得分:1)

C ++ 11提供了一个模板类型std::aligned_union,它采用了一系列类型。 aligned_union::type是一种具有足够存储空间和对齐的类型,可以作为任何给定类型的存储。

这就是您为数据创建存储的方式。除此之外你需要的只是一个整数,它告诉你存储哪个值。

template<typename ...Types>
struct variant
{
private:
  uint8_t index;
  typename std::aligned_union<Types...>::type storage;
};

您使用展示位置new将各个元素分配到storage提供的存储空间内的特定类型。