Listing 1: Demonstrates type_name function added to Fernando Cacciola’s variant_t

// test0() shows the basic construction and
// use of variant_t with various types.
void test0()
{
  variant_t _int ( 2 ) ;
  variant_t _dbl ( 3.14 ) ;
  variant_t 
  _str ( string ( "This is a string" ) ) ;
  // IMPORTANT NOTE: The above statement 
  // COULD NOT have been 
  // variant_t _str ( "This is a string" );
  // The expression "This is a string" is
  // of type const char *, which is just a
  // pointer. The copy of a pointer is just
  // another pointer of the same value, not
  // a new membory block with a copy of the
  // contents of the original block.
  // The value copied and stored in _str
  // would be the pointer value and not the
  // character array contents.

  cout << "BEGIN test0" << endl ;
  #ifdef NO_EXPLICIT_MEMBER_TPL_INSTANTIATION
    cout << variant_cast<int>(_int) 
         << " is of type " << _int.type_name()
         << endl ;
    cout << variant_cast<double>(_dbl)
         << " is of type " << _dbl.type_name()
         << endl ;
    cout << variant_cast<string>(_str)
         << " is of type " << _str.type_name()
         << endl ;
  #else
    cout << (int)   _int << " is of type "
         << _int.type_name() << endl ;
    cout << (double)_dbl << " is of type "
         << _dbl.type_name() << endl ;
    cout << (string)_str << " is of type "
         << _str.type_name() << endl ;
  #endif
  cout << "END test0"   << endl << endl ;

 _dbl = _int;

 cout << "_dbl = " << variant_cast<int>(_dbl)
      << endl;
 cout << "_int = " << variant_cast<int>(_dbl)
      << endl;
}
— End of Listing —