boost::anyとType Erasure

復習しないと復習しないと

Type Erasureの本質は型を消すことにあるんじゃなくて

消した型をtype safeに元に戻せることにあるんじゃないのかな・・

ぐぐって見るとstruct anyのほうは結構あるのにany_castのほうはあまり触れてないのよね

というわけでサンプルを書いてみるテスト



#include <tchar.h>
#include <string>

#include <boost/type_traits.hpp>

struct any
{
	struct placeholder
	{
		virtual ~placeholder()
		{
		}
		virtual const std::type_info& type() const = 0;
	};

	template <typename T>
	struct holder
		:public placeholder
	{
		holder(const T& value)
			:value_(value)
		{
		}
		virtual const std::type_info& type() const
		{
			return typeid(T);
		}
		T value_;
	};

	template <typename T>
	any(const T& value)
		:holder_(new holder<T>(value))
	{
	}

	~any()
	{
		delete holder_;
	}
	placeholder* holder_;

	template <typename T>
	friend T any_cast(const any& a);
};

template <typename T>
T any_cast(const any& a)
{
	typedef typename boost::remove_reference<T>::type cast_type;

	if(typeid(cast_type)!=a.holder_->type())
		printf("cast error\n");

	return (static_cast<any::holder<cast_type>*>(a.holder_))->value_;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int i=5;
	any a(i);
	int j=any_cast<int>(a);
	printf("j=%d\n",j);

	std::string s("abc");
	any b(s);
	std::string t=any_cast<std::string>(b);
	printf("t=%s\n",t.c_str());

	struct vec
	{
		long x;
		long y;
	};

	vec v;
	v.x=10;
	v.y=20;
	any c(v);
	printf("vec=(%d,%d)\n",any_cast<vec>(c).x,any_cast<vec>(c).y);
}