Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is equivalent of C#'s is and as operator in C++/CLI [duplicate]

Tags:

c++-cli

I've read somewhere on MSDN that the equivalent to C#'s "is" keyword would be dynamic_cast, but that's not really equivalent: It doesn't work with value types or with generic parameters. For example in C# I can write:

void MyGenericFunction<T>()
{
    object x = ...
    if (x is T)
        ...;
}

If I try the "equivalent" C++/CLI:

generic<class T>
void MyGenericFunction()
{
    object x = ...
    if (dynamic_cast<T>(x))
       ...;
}

I get a compiler error "error C2682: cannot use 'dynamic_cast' to convert from 'System::Object ^' to 'T'".

The only thing I can think of is to use reflection:

if (T::typeid->IsAssignableFrom(obj->GetType()))

Is there a simpler way to do this?

like image 777
Niki Avatar asked Apr 03 '09 07:04

Niki


People also ask

What is equal to equal to in C?

The result type for these operators is bool . The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( !=

What is equivalent to classes in C?

The closest thing you can get is a struct .

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.

What does %d do in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

It's on MSDN:

How to: Implement is and as C# Keywords in C++

In a nutshell, you need to write a helper function like so:

template < class T, class U > 
Boolean isinst(U u) {
   return dynamic_cast< T >(u) != nullptr;
}

and call it like this:

Object ^ o = "f";
if ( isinst< String ^ >(o) )
    Console::WriteLine("o is a string");
like image 188
Guido Domenici Avatar answered Oct 06 '22 00:10

Guido Domenici