简体   繁体   中英

How can I implement variant types in the CLR/Managed C++?

In the .net CLR Object is the base for all class objects, but not basic types (eg int, float etc). How can I use basic types like Object? Ie Like Boost.Variant ?

Eg like :-

object intValue( int(27) );
if (intValue is Int32)
    ...

object varArray[3];
varArray[0] = float(3.141593);
varArray[1] = int(-1005);
varArray[2] = string("String");

object , via boxing, is the effective (root) base-class of all .NET types. That should work fine - you just need to use is or GetType() to check the types...

object[] varArray = new object[3];
varArray[0] = 3.141593F;
varArray[1] = -1005;
varArray[2] = "String";

Since you mentioned you're in C++/CLI, you should be able to do:

array<Object^>^ varArray =  gcnew array<Object^>(3);

varArray[0] = 3.141593;
varArray[1] = -1005;
varARray[2] = "String";

double val = *reinterpret_cast<double^>(varArray[0]);
object varArray[3] = new object[3];
varArray[0] = 3.141593;
varArray[1] = -1005;
varArray[2] = "String";

Thanks for the boxing answer. I need to box my return value, eg

    Object ^ createFromString(String ^ value)
    {
         Int32 i( Convert::ToInt32(value) );
         return static_cast< Object ^ >(i);
    }

I need to box the return value by casting to an Object pointer. Intuitive! :)

And retrieve as:

    void writeValue(Object ^ value, BinaryWriter ^ strm)
    {
        Int32 i( *dynamic_cast< Int32 ^ >(value) );
        strm->Write(i);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM