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++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

poj3468(线段树成段更新模板题)

题意:包括两个操作:1、将[a.b]上的数字加上v;2、查询区间[a,b]上的和 下面的介绍是下解题思路: 首先介绍  lazy-tag思想:用一个变量记录每一个线段树节点的变化值,当这部分线段的一致性被破坏我们就将这个变化值传递给子区间,大大增加了线段树的效率。 比如现在需要对[a,b]区间值进行加c操作,那么就从根节点[1,n]开始调用update函数进行操作,如果刚好执行到一个子节点,

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

uva 1342 欧拉定理(计算几何模板)

题意: 给几个点,把这几个点用直线连起来,求这些直线把平面分成了几个。 解析: 欧拉定理: 顶点数 + 面数 - 边数= 2。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#inc