Variant's, Any and void* issue

Zack Rusin zack at kde.org
Sat Apr 24 21:23:34 BST 2004


Hey,

QVariant is nice, but it's not extendible which is why we still have 
code in some places which uses void* to store objects of any type. It 
would be ok, if not that using void* makes deleting the holded object 
impossible.  

Here's one solution that I'm using locally for some things and it looks 
that we'll switch kjsembed to it as well.

It's an Any class. It's essentially Boost::any but with addition of the 
ability to type safe delete the held object.

And example usage looks as follows :

QValueList< Any > anyList;
anyList.append( 5 );
anyList.append( static_cast<const char*>( "some string" ) );
anyList.append( 13.33333 );
anyList.append( new float( 4.4 ) );

QValueList< Gadget::Any >::iterator itr;
for ( itr = anyList.begin(); itr != anyList.end(); ++itr ) {
      kdDebug()<< "Iterator holds " << (*itr).type().name() <<endl;
      if ( (*itr ).type() == typeid(int) ) {
          kdDebug()<<"\tValue is "<< any_cast<int>( *itr ) <<endl;
      } else if ( (*itr ).type() == typeid(double) ) {
          kdDebug()<<"\tValue is "<< any_cast<double>( *itr ) <<endl;
      } else if ( (*itr ).type() == typeid(const char*) ) {
        kdDebug()<<"\tValue is "<< any_cast<const char*>( *itr ) <<endl;
      } else if ( (*itr ).type() == typeid(float*) ) {
       kdDebug()<<"\tValue is "<< *( any_cast<float*>( *itr ) )  <<endl;
      }
      ( *itr ).deleteObject();
}

Code with an example is available at 
http://www.automatix.de/~zack/any.tar.bz2 .

There's still a lot of cool things that we could use it for but now this 
is a heads-up saying that if need a typesafe void* you really should 
use this thing.

Zack

-- 
Maintenance-free: When it breaks, it can't be fixed...




More information about the kde-core-devel mailing list