任意数据类型

梦想游戏人
目录:
C/C++

通过类和 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;
};
Scroll Up