Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use dynamic_cast with generics

I have a generic class Client which has a single type parameter. The type parameter is any reference type derived from Base. So I declare the class as below:

generic <class T>
where T : Base, gcnew()
public ref class Client {
  T val;
  void SetVal(Base ^bval){

    val = dynamic_cast<T>(bval);  // error C2682: cannot use 'dynamic_cast' to convert from 'Base ^' to 'T'

  }  
};

Why do I get a compile error when using dynamic_cast to convert from Base to one of its derived classes? I was expecting the cast to compile but fail at runtime (by returning nullptr) in case the argument was of incorrect type.

like image 627
Agnel Kurian Avatar asked Oct 12 '25 06:10

Agnel Kurian


1 Answers

Try dynamic_cast <T^>.

Pointers have to be cast to other pointers, handles to other handles, and so forth.

like image 195
Ben Voigt Avatar answered Oct 15 '25 06:10

Ben Voigt