FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
October 01, 2000

An Improved Variant Type Based on Member Templates

(Page 3 of 8)
October 2000/An Improved Variant Type Based on Member Templates/Listing 2

Listing 2: Definition of class variant1_t

// This variant copies the original
// value into its own data to
// preserve the value when the
// original variable goes out of scope.
struct variant1_t
{
   variant1_t():data(NULL){}
  ~variant1_t(){ free(data); }

  template<typename T> variant1_t ( T v )
    :data(malloc(sizeof(T)))
    { memcpy ( data , &v , sizeof(T)); }

  template<typename T> operator T () const
    { return * reinterpret_cast<T*>(data); }

  void* data ;
} ;

// usage:
variant1_t _int ( 2 ) ;
variant1_t _dbl ( 3.14 ) ;
cout << (int)   _int << endl ;
cout << (double)_dbl << endl ;

Previous Page | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 Next Page
RELATED ARTICLES
No Related Articles
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK