Representation and basic construction of a generalized union type.
From Mechanism to Method
Valued Conversions
Kevlin Henney
Listing 1. Representation and basic construction of a generalized union type.
class any
{
public:
any()
: content(0)
{
}
~any()
{
delete content;
}
const std::type_info &type_info() const
{
return content
? content->type_info()
: typeid(void);
}
...
private:
class placeholder
{
public:
virtual ~placeholder()
{
}
virtual const std::type_info &
type_info() const = 0;
virtual placeholder *clone() const = 0;
};
template<typename value_type>
class holder : public placeholder
{
public:
holder(const value_type &value)
: held(value)
{
}
virtual const std::type_info &type_info() const
{
return typeid(value_type);
}
virtual placeholder *clone() const
{
return new holder(held);
}
const value_type held;
};
placeholder *content;
};