任意数据类型

通过类和 union 的包装 实现任意数据类型


class Wrapper
{
public:
	Wrapper(){}
	Wrapper(int arg)
	{
		this->i = arg;
		this->_type = TYPE::INT;
	}
	Wrapper(float arg)
	{
		this->f = arg;
		this->_type = TYPE::FLOAT;
	}
	Wrapper(bool arg)
	{
		this->b = arg;
		this->_type = TYPE::BOOL;

	}
	Wrapper(double arg)
	{
		this->d = arg;
		this->_type = TYPE::DOUBLE;

	}
	int toInt()
	{
		if (this->_type == TYPE::INT)
		{
			return this->i;
		}
		if (this->_type == TYPE::FLOAT)
		{
			return (int)(this->f);
		}
		if (this->_type == TYPE::DOUBLE)
		{
			return (int)(this->d);
		}
		if (this->_type == TYPE::BOOL)
		{
			return   this->b == 0 ? false : true;
		}

	}


	float toFloat()
	{
		if (this->_type == TYPE::INT)
		{
			return (float)this->i;
		}
		if (this->_type == TYPE::FLOAT)
		{
			return (this->f);
		}
		if (this->_type == TYPE::DOUBLE)
		{
			return (float)(this->d);
		}
		if (this->_type == TYPE::BOOL)
		{
			return   this->b == false ? 0.0f : 1.0f;
		}

	}


	double toDouble()
	{
		if (this->_type == TYPE::INT)
		{
			return (double)this->i;
		}
		if (this->_type == TYPE::FLOAT)
		{
			return (double)this->f;
		}
		if (this->_type == TYPE::DOUBLE)
		{
			return this->d;
		}
		if (this->_type == TYPE::BOOL)
		{
			return   this->b == false ? 0.0 : 1.0;
		}

	}


	bool toBool()
	{
		if (this->_type == TYPE::INT)
		{
			return  this->i == 0 ? false : true;;
		}
		if (this->_type == TYPE::FLOAT)
		{
			return  this->f < 0.0000000001 ? false : true;;
		}
		if (this->_type == TYPE::DOUBLE)
		{
			return  this->d < 0.0000000001 ? false : true;;
		}
		if (this->_type == TYPE::BOOL)
		{
			return   this->b;
		}

	}

	union
	{
		int i = 0;
		float f;
		bool b;
		double d;
	};
	enum class TYPE
	{
		INT,
		FLOAT,
		DOUBLE,
		BOOL
	};
	operator int() { return  this->toInt(); }
	operator float() { return  this->toFloat(); }
	operator bool() { return this->toBool(); }
	operator double() { return this->toDouble(); }

private:
	TYPE _type;
};

 

转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/736363

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值