[C++] 实现Union

前几天学了replacement new写的小玩意

cpp 复制代码
#include <iostream>
#include <functional>
#include <string>

// 可能因为const char*类型的缘故
// 用const ArgsT&&...会报错

// 测试用类
struct Test
{
	Test()
	{
		std::cout << "constructed" << std::endl;
	};

	~Test()
	{
		std::cout << "destructed" << std::endl;
	};
};

// 析构器
template <typename T = char[]>
struct Destructor
{
	void operator()(void *ptr)
	{
		T *obj = (T *)ptr;
		// 调用析构函数
		obj->~T();
	};
};

// 基础类型没有析构函数
#define BASE_TYPE(type)            \
	template <>                    \
	struct Destructor<type>        \
	{                              \
		void operator()(void *) {} \
	};

BASE_TYPE(char[]);
BASE_TYPE(int);

//构造器
template <typename T>
struct Constructor
{
	template <typename... ArgsT>
	void operator()(void *ptr, ArgsT... args)
	{
		T *obj = (T *)ptr;
		// replacement new
		new (obj) T(std::forward<ArgsT>(args)...);
	};
};

// 变体类
template <std::size_t size>
struct Variant
{
	char memory[size] = {};
	std::function<void(void *)> destructor = Destructor<>();

	// 调用对象的析构函数
	~Variant()
	{
		destructor(memory);
		destructor = Destructor<>();
	}

	// 构造对象
	template <typename NewT, typename... ArgsT>
	void construct(ArgsT... args)
	{
		destructor(memory);
		destructor = Destructor<NewT>();

		Constructor<NewT> c;
		c(memory, std::forward<ArgsT>(args)...);
	}

	// 获取对象
	template <typename T>
	T &get()
	{
		T *obj = (T *)memory;
		return *obj;
	}
	template <typename T>
	const T &get() const
	{
		const T *obj = (const T *)memory;
		return *obj;
	}
};

int main(int argc, char *argv[])
{
	// 测试
	/*Destructor<Test> d;
	Test t;
	d(&t);
	Constructor<Test> c;
	c(&t);*/

	// 使用例
	Variant<32> v;
	v.construct<Test>();
	v.construct<std::string, std::string>("aaa");
	std::cout << v.get<std::string>() << std::endl;
	v.construct<int, int>(666);
	std::cout << v.get<int>() << std::endl;

	return 0;
}
相关推荐
虾球xz10 分钟前
CppCon 2015 学习:3D Face Tracking and Reconstruction using Modern C++
开发语言·c++·学习·3d
small_wh1te_coder1 小时前
c语言超详细知识点总结 1500行手写源码 持续更新中ing 从25年5月到6月5日
c++·c
SteveDraw3 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
十五年专注C++开发3 小时前
设计模式之单例模式(二): 心得体会
开发语言·c++·单例模式·设计模式
?!7143 小时前
算法打卡第18天
c++·算法
zh_xuan3 小时前
c++ std::pair
开发语言·c++
CodeWithMe4 小时前
【C/C++】EBO空基类优化介绍
开发语言·c++
k要开心4 小时前
从C到C++语法过度1
开发语言·c++
whoarethenext4 小时前
使用 C/C++的OpenCV 实时播放火柴人爱心舞蹈动画
c语言·c++·opencv
能工智人小辰5 小时前
Codeforces Round 509 (Div. 2) C. Coffee Break
c语言·c++·算法