// This variant holds the copy of the original value in
// an object of a class specially designed to ensure proper copy
// and conversion.
class variant2_t
{
public :
variant2_t() : data ( NULL ) {}
~variant2_t() { delete data; }
template<typename T> variant2_t ( T v )
:data(new Impl<T>(v))
{}
template<typename T> operator T () const
{ return * CastFromBase<T>(data); }
private :
struct ImplBase
{
virtual ~ImplBase() {}
} ;
template<typename T>
struct Impl : ImplBase
{
Impl ( T v ) : data ( v ) {}
T data ;
} ;
template<typename T> Impl<T>* CastFromBase(ImplBase* v)
{
Impl<T>* p = dynamic_cast<Impl<T>*>(v);
if ( p == NULL )
throw invalid_argument ( typeid(T).name() +
string(" is not a valid type")
) ;
return p ;
}
ImplBase* data ;
} ;
// usage:
variant2_t _int( 2 ) ;
variant2_t _dbl( 3.14 ) ;
variant2_t _str( string( "Hellow"));
cout << (int) _int << endl ;
cout << (double)_dbl << endl ;
cout << (string&)_str << endl ;