c++ - 可变模板化结构/boost::variant 是如何实现的

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

是否可以实现类似下面的效果

DifferentTypesInOne<string, int, double> variant_obj;

variant_obj 中有 string、int 和 double 类型的变量。

我知道这类似于 boost::variant。我之前搜索过有关它的问题,但我无法偶然发现可以解释该类如何使用可变参数模板来存储所有类型元素的解释。特别是我问我如何定义一个 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;
};

这是草图;详情 these articles是一本好书。

如果你不需要constexpr -ness,你可以存储一个std::aligned_union_t<0, Ts...>作为存储,使用placement new,更简单。

关于c++ - 可变模板化结构/boost::variant 是如何实现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36211708/

相关文章:

c++ - 类前向声明​​ C++

c++ - 使用 OpenCV C++ 进行楼梯检测的线拟合

c++ - 模板元编程 : checking for existence of a function defined later

c++ - 获取传递给模板函数的 std::map 的值类型

C++ 无法为高阶函数派生模板参数

c++ - 使用自定义标志编译 XCode 5 项目

c++ - std::shared_ptr 和初始化列表

c++ - 调用模板化成员函数与模板化全局函数在通用工厂中创建对象

C++11 regex_match 不匹配它必须的

c++ - 模板参数列表中的额外 typename 关键字 : is it valid or not?