variant (C++ 模板元编程)

2023-11-05 03:36
文章标签 模板 c++ 编程 variant

本文主要是介绍variant (C++ 模板元编程),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

std::variant

可以理解为一个会自动清除空间的union,保证了赋值时内存的正确性,能够自动进行析构。

通过get可传入下标或者type来获取值,但是不安全,如果传入类型于当前类型不一致时会引发错误。

可以通过get_if传入下标或者值和variant指针来安全获得值。

有类模板variant_alternative来获取第几个属性的type,以及类模板variant_size来获取variant中存放了多少个属性。

  • variant
  • get< type >
  • get< N >
  • variant_alternative
  • variant_size
  • operator =
int main() {std::variant<int, float> a;a = 1;auto int_value = std::get<int>(a);std::cout << int_value << "\n";try {auto float_value = std::get<float>(a);} catch (const std::bad_variant_access &e) {std::cout << e.what() << "\n";}std::cout << std::holds_alternative<int>(a) << " "<< std::holds_alternative<float>(a) << "\n";a = 1.1f;std::cout << std::holds_alternative<int>(a) << " "<< std::holds_alternative<float>(a) << "\n";std::cout << std::get<float>(a) << " " << std::get<1>(a) << "\n";// std::cout << std::get<int>(a) << " " << std::get<0>(a) << "\n";std::cout << std::get_if<0>(&a) << " " << std::get_if<int>(&a) << "\n";std::cout << std::get_if<1>(&a) << " " << std::get_if<float>(&a) << "\n";std::variant_alternative<1, decltype(a)>::type f = 1.2;std::cout << f << "\n";std::cout << std::variant_size_v<decltype(a)> << "\n";return 0;
}

sample::variant

存储结构

union模板一层一层嵌套,即可得到我们的variant存储结构,整体的内存占用情况为sizeof(largestType<Ts...>)

template<typename ...Ts> union __union;template<typename T, typename ...Ts>
union __union<T, Ts...> {using type = __union;using rest_type = __union<Ts...>;using value_type = T;T value_;rest_type rest_;template<typename Tv>requires std::is_same_v<std::decay_t<Tv>, T>__union(Tv&& value) : value_(std::forward<Tv>(value)) {}template <typename Tv>__union(Tv&& rest) : rest_(std::forward<Tv>(rest)) {}__union() {}~ __union() {}
};template<typename T>
union __union<T> {using type = __union;using value_type = T;T value_;template<typename Tv>requires std::is_same_v<std::decay_t<Tv>, T>__union(Tv&& value) : value_(std::forward<Tv>(value)) {}__union() {}~ __union() {}
};

简单测试访问一下看看:

int a = 114;
auto u1 = __union<short int, int, unsigned int, long long, float, double>(a);
std::cout << u1.value_ << " " << u1.rest_.value_ << " " << u1.rest_.rest_.value_ << " "<< u1.rest_.rest_.rest_.value_ << " " << u1.rest_.rest_.rest_.rest_.value_ << " "<< u1.rest_.rest_.rest_.rest_.rest_.value_ << "\n";const double b = 115.514;
auto u2 = __union<short int, int, unsigned int, long long, float, double>(b);
std::cout << u2.value_ << " " << u2.rest_.value_ << " " << u2.rest_.rest_.value_ << " "<< u2.rest_.rest_.rest_.value_ << " " << u2.rest_.rest_.rest_.rest_.value_ << " "<< u2.rest_.rest_.rest_.rest_.rest_.value_ << "\n";std::string str = "lifehappy";
auto u3 = __union<int, double, std::string>(std::move(str));
std::cout << u3.value_ << " " << u3.rest_.value_ << " " << u3.rest_.rest_.value_ << " : __union\n";
std::cout << str << " : str\n";

114 114 114 4294967410 1.59748e-43 2.122e-314
-30409 1614907703 1614907703 4637828992051808567 5.5783e+19 115.514
1701210476 4.06896e+233 lifehappy : __union
: str

variant

template<typename ...Ts>
struct variant {using type = variant;using data_type = __union<Ts...>;__union<Ts...> data_;template<typename Tv>variant(Tv&& data) : data_(std::forward<Tv>(data)) {}variant() {}~ variant() {}
};

variant_alternative

template<int N, typename ...Ts> struct variant_alternative {};template<int N, typename ...Ts>
struct variant_alternative<N, variant<Ts...>>: variant_alternative<N, typename variant<Ts...>::data_type> {};template<int N, typename ...Ts>
struct variant_alternative<N, __union<Ts...>>: variant_alternative<N - 1, typename __union<Ts...>::rest_type> {};template<typename ...Ts>
struct variant_alternative<0, __union<Ts...>> {using type = __union<Ts...>::value_type;
};template<int N, typename ...Ts>
using variant_alternative_t = variant_alternative<N, Ts...>::type;

variant_size

template<typename ...Ts> struct variant_size {};template<typename ...Ts>
struct variant_size<variant<Ts...>>: std::integral_constant<int, sizeof...(Ts)> {};template<typename ...Ts>
constexpr static int variant_size_v = variant_size<Ts...>::value;

get< type > 、get< N >

这里的实现并不会像std::variant一样,即可以把我们的实现认为就是一个union

get< N >

template<int N, typename T>
struct get_impl {static auto&& get(T &data) {return get_impl<N - 1, typename T::rest_type>::get(data.rest_);}
};template<typename T>
struct get_impl<0, T> {static T::value_type& get(T &data) {return data.value_;}
};template<int N, typename T>
static auto&& get(T &var) {return get_impl<N, typename T::data_type>::get(var.data_);
}

get< type >

template<typename T, typename Tv>
struct get_type_impl {static auto&& get(Tv &data) {return get_type_impl<T, typename Tv::rest_type>::get(data.rest_);}
};template<typename Tv>
struct get_type_impl<typename Tv::value_type, Tv> {static Tv::value_type& get(Tv &data) {return data.value_;}
};template<typename T, typename Tv>
static auto&& get(Tv &var) {return get_type_impl<T, typename Tv::data_type>::get(var.data_);
}

operator =

这里也是variant最重要的功能了,能够在赋值的时候自动析构原来保存的值。

先看不加析构函数的版本:

template<typename Tv>
variant& operator = (Tv&& data) {new (&data_) data_type(std::forward<Tv>(data));return *this;
}

TEST

struct Test {~ Test() {std::cout << "~ Test()\n";}
};Test a, b;
variant<int, long long, Test> variant_test(a);
std::cout << "OK\n";
variant_test = b;
std::cout << "OK\n";

OK
OK
~ Test()
~ Test()

只有最后a、b的两次析构,缺少了赋值时和销毁variant时的析构调用。

要能够析构,那么势必我们需要保存当前的type,为了方便,这里直接使用一个int变量来保存type所对应的下标,

同时实现一个类模板,获取当前值在列表中的位置。

template<typename Tu, typename T> struct type_index_impl: std::integral_constant<int, type_index_impl<typename Tu::rest_type, T>::value + 1> {};template<typename Tu>
struct type_index_impl<Tu, typename Tu::value_type>: std::integral_constant<int, 0> {};template<typename Tu, typename T>
constexpr static int type_index = type_index_impl<Tu, T>::value;

得到所有类型的析构函数,由于variant的类型是动态加载的,考虑将所有类型的destructor存下来,按需调用:

std::function<void(void *)> destructors[sizeof...(Ts)] ={ [](void *ptr) { static_cast<Ts*>(ptr)->~Ts(); }... };

接着稍微修改一下operator =、~variant()

template<typename Tv>
variant& operator = (Tv&& data) {if (~type_) {destructors[type_](&data_);}new (&data_) data_type(std::forward<Tv>(data));type_ = type_index<data_type, std::decay_t<Tv>>;return *this;
}~ variant() {if (~type_) {destructors[type_](&data_);}
}

TEST

struct Test1 {~ Test1() {std::cout << "~ Test1()\n";}
}a;struct Test2 {~ Test2() {std::cout << "~ Test2()\n";}
}b;variant<int, long long, Test1, Test2> variant_test(a);
std::cout << "OK\n";
variant_test = b;
std::cout << "OK\n";
OK
Test1()
OK
Test2()
Test2()
Test1()

Code

#include <iostream>
#include <string>
#include <type_traits>
#include <functional>template<typename ...Ts> union __union;template<typename T, typename ...Ts>
union __union<T, Ts...> {using type = __union;using rest_type = __union<Ts...>;using value_type = T;T value_;rest_type rest_;template<typename Tv>requires std::is_same_v<std::decay_t<Tv>, T>__union(Tv&& value) : value_(std::forward<Tv>(value)) {}template <typename Tv>__union(Tv&& rest) : rest_(std::forward<Tv>(rest)) {}__union() {}~ __union() {}
};template<typename T>
union __union<T> {using type = __union;using value_type = T;T value_;template<typename Tv>requires std::is_same_v<std::decay_t<Tv>, T>__union(Tv&& value) : value_(std::forward<Tv>(value)) {}__union() {}~ __union() {}
};template<typename Tu, typename T> struct type_index_impl: std::integral_constant<int, type_index_impl<typename Tu::rest_type, T>::value + 1> {};template<typename Tu>
struct type_index_impl<Tu, typename Tu::value_type>: std::integral_constant<int, 0> {};template<typename Tu, typename T>
constexpr static int type_index = type_index_impl<Tu, T>::value;template<typename ...Ts>
struct variant {using type = variant;using data_type = __union<Ts...>;__union<Ts...> data_;int type_{-1};std::function<void(void *)> destructors[sizeof...(Ts)] ={ [](void *ptr) { static_cast<Ts*>(ptr)->~Ts(); }... };template<typename Tv>variant(Tv&& data) : data_(std::forward<Tv>(data)),type_(type_index<data_type, std::decay_t<Tv>>) {}template<typename Tv>variant& operator = (Tv&& data) {if (~type_) {destructors[type_](&data_);}new (&data_) data_type(std::forward<Tv>(data));type_ = type_index<data_type, std::decay_t<Tv>>;return *this;}variant() {}~ variant() {if (~type_) {destructors[type_](&data_);}}
};template<int N, typename ...Ts> struct variant_alternative {};template<int N, typename ...Ts>
struct variant_alternative<N, variant<Ts...>>: variant_alternative<N, typename variant<Ts...>::data_type> {};template<int N, typename ...Ts>
struct variant_alternative<N, __union<Ts...>>: variant_alternative<N - 1, typename __union<Ts...>::rest_type> {};template<typename ...Ts>
struct variant_alternative<0, __union<Ts...>> {using type = __union<Ts...>::value_type;
};template<int N, typename ...Ts>
using variant_alternative_t = variant_alternative<N, Ts...>::type;template<typename ...Ts> struct variant_size {};template<typename ...Ts>
struct variant_size<variant<Ts...>>: std::integral_constant<int, sizeof...(Ts)> {};template<typename ...Ts>
constexpr static int variant_size_v = variant_size<Ts...>::value;template<int N, typename T>
struct get_n_impl {static auto&& get(T &data) {return get_n_impl<N - 1, typename T::rest_type>::get(data.rest_);}
};template<typename T>
struct get_n_impl<0, T> {static T::value_type& get(T &data) {return data.value_;}
};template<int N, typename T>
static auto&& get(T &var) {return get_n_impl<N, typename T::data_type>::get(var.data_);
}template<typename T, typename Tv>
struct get_type_impl {static auto&& get(Tv &data) {return get_type_impl<T, typename Tv::rest_type>::get(data.rest_);}
};template<typename Tv>
struct get_type_impl<typename Tv::value_type, Tv> {static Tv::value_type& get(Tv &data) {return data.value_;}
};template<typename T, typename Tv>
static auto&& get(Tv &var) {return get_type_impl<T, typename Tv::data_type>::get(var.data_);
}int main() {int a = 114;auto u1 = __union<short int, int, unsigned int, long long, float, double>(a);std::cout << u1.value_ << " " << u1.rest_.value_ << " " << u1.rest_.rest_.value_ << " "<< u1.rest_.rest_.rest_.value_ << " " << u1.rest_.rest_.rest_.rest_.value_ << " "<< u1.rest_.rest_.rest_.rest_.rest_.value_ << "\n";const double b = 115.514;auto u2 = __union<short int, int, unsigned int, long long, float, double>(b);std::cout << u2.value_ << " " << u2.rest_.value_ << " " << u2.rest_.rest_.value_ << " "<< u2.rest_.rest_.rest_.value_ << " " << u2.rest_.rest_.rest_.rest_.value_ << " "<< u2.rest_.rest_.rest_.rest_.rest_.value_ << "\n";std::string str1 = "lifehappy";auto u3 = __union<int, double, std::string>(std::move(str1));std::cout << u3.value_ << " " << u3.rest_.value_ << " " << u3.rest_.rest_.value_ << " : __union\n";std::cout << str1 << " : str\n";auto v3 = variant<int, double, std::string>();std::cout << std::is_same_v<int, variant_alternative_t<0, decltype(v3)>> << " "<< std::is_same_v<double, variant_alternative_t<1, decltype(v3)>> << " "<< std::is_same_v<std::string, variant_alternative_t<2, decltype(v3)>> << "\n";std::cout << std::is_same_v<int, variant_alternative_t<0, decltype(u3)>> << " "<< std::is_same_v<double, variant_alternative_t<1, decltype(u3)>> << " "<< std::is_same_v<std::string, variant_alternative_t<2, decltype(u3)>> << "\n";std::cout << std::is_same_v<variant_alternative_t<0, decltype(v3)>, variant_alternative<0, decltype(v3)>::type> << " "<< std::is_same_v<variant_alternative_t<1, decltype(v3)>, variant_alternative<1, decltype(v3)>::type> << " "<< std::is_same_v<variant_alternative_t<2, decltype(v3)>, variant_alternative<2, decltype(v3)>::type> << "\n";std::cout << std::is_same_v<variant_alternative_t<0, decltype(u3)>, variant_alternative<0, decltype(u3)>::type> << " "<< std::is_same_v<variant_alternative_t<1, decltype(u3)>, variant_alternative<1, decltype(u3)>::type> << " "<< std::is_same_v<variant_alternative_t<2, decltype(u3)>, variant_alternative<2, decltype(u3)>::type> << "\n";std::cout << variant_size<decltype(v3)>::value << " " << variant_size_v<decltype(v3)> << "\n";variant<int, unsigned int, long long, double, std::string> v4((int)114514);std::cout << get_n_impl<0, decltype(v4.data_)>::get(v4.data_) << " " << get_n_impl<1, decltype(v4.data_)>::get(v4.data_) << " "<< get_n_impl<2, decltype(v4.data_)>::get(v4.data_) << " " << get_n_impl<3, decltype(v4.data_)>::get(v4.data_) << " "<< get_n_impl<4, decltype(v4.data_)>::get(v4.data_) << "\n";std::cout << get<0>(v4) << " " << get<1>(v4) << " " << get<2>(v4) << " " << get<3>(v4) << " " << get<4>(v4) << "\n";std::cout << get_type_impl<int, decltype(v4.data_)>::get(v4.data_) << " " << get_type_impl<unsigned int, decltype(v4.data_)>::get(v4.data_) << " "<< get_type_impl<long long, decltype(v4.data_)>::get(v4.data_) << " " << get_type_impl<double, decltype(v4.data_)>::get(v4.data_) << " "<< get_type_impl<std::string, decltype(v4.data_)>::get(v4.data_) << "\n";std::cout << get<int>(v4) << " " << get<unsigned int>(v4) << " " << get<long long>(v4) << " " << get<double>(v4) << " " << get<std::string>(v4) << "\n";int int1 = 1;const int int2 = 1;int &int3 = int1;std::cout << variant<int, float, std::string>().type_ << " "<< variant<int, float, std::string>(int1).type_ << " "<< variant<int, float, std::string>(int2).type_ << " "<< variant<int, float, std::string>(int3).type_ << " "<< variant<int, float, std::string>(1.1f).type_ << " "<< variant<int, float, std::string>(std::string("lifehappy")).type_ << "\n";struct Test1 {~ Test1() {std::cout << "~ Test1()\n";}}ta;struct Test2 {~ Test2() {std::cout << "~ Test2()\n";}}tb;variant<int, long long, Test1, Test2> variant_test(ta);std::cout << "OK\n";variant_test = tb;std::cout << "OK\n";return 0;
}

这篇关于variant (C++ 模板元编程)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/347151

相关文章

关于C++中的虚拟继承的一些总结(虚拟继承,覆盖,派生,隐藏)

1.为什么要引入虚拟继承 虚拟继承是多重继承中特有的概念。虚拟基类是为解决多重继承而出现的。如:类D继承自类B1、B2,而类B1、B2都继承自类A,因此在类D中两次出现类A中的变量和函数。为了节省内存空间,可以将B1、B2对A的继承定义为虚拟继承,而A就成了虚拟基类。实现的代码如下: class A class B1:public virtual A; class B2:pu

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

零基础STM32单片机编程入门(一)初识STM32单片机

文章目录 一.概要二.单片机型号命名规则三.STM32F103系统架构四.STM32F103C8T6单片机启动流程五.STM32F103C8T6单片机主要外设资源六.编程过程中芯片数据手册的作用1.单片机外设资源情况2.STM32单片机内部框图3.STM32单片机管脚图4.STM32单片机每个管脚可配功能5.单片机功耗数据6.FALSH编程时间,擦写次数7.I/O高低电平电压表格8.外设接口

16.Spring前世今生与Spring编程思想

1.1.课程目标 1、通过对本章内容的学习,可以掌握Spring的基本架构及各子模块之间的依赖关系。 2、 了解Spring的发展历史,启发思维。 3、 对 Spring形成一个整体的认识,为之后的深入学习做铺垫。 4、 通过对本章内容的学习,可以了解Spring版本升级的规律,从而应用到自己的系统升级版本命名。 5、Spring编程思想总结。 1.2.内容定位 Spring使用经验

C++入门01

1、.h和.cpp 源文件 (.cpp)源文件是C++程序的实际实现代码文件,其中包含了具体的函数和类的定义、实现以及其他相关的代码。主要特点如下:实现代码: 源文件中包含了函数、类的具体实现代码,用于实现程序的功能。编译单元: 源文件通常是一个编译单元,即单独编译的基本单位。每个源文件都会经过编译器的处理,生成对应的目标文件。包含头文件: 源文件可以通过#include指令引入头文件,以使

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共