Wrapping a unmanaged template class in a managed generic class

G

Guest

Hey,

I am trying to wrap an unmanaged library in managed c++ so that I can use
this library in other .NET languages, such as C#. I've been successful for
the most part this far, but I'm having a hard time figuring out how to wrap
template classes. I'm getting an C3231 compile error when I try to use the
generic type as a template type.

Here's an example from the MSDN C3231 compile error site:

template <class T> class A;

generic <class T>
ref class C {
void f() {
A<T> a; // C3231
}
};

Does anyone know how to work around this?

Best regards,
Rune Vistnes
 
D

Dick Swager

Me too!

I found this article:
http://www.codeproject.com/managedcpp/cppcligenerics.asp

It indicates that generics can be used for this very purpose. And it demos
the use of typeid:

generic<typename T> static INumericalOperations<T>^ GetNumericalAdapter()
{
Type^ typ = T::typeid;
if( typ == int::typeid)
{
return dynamic_cast<INumericalOperations<T>^>(gcnew
IntNumericalAdapter());
}
if( typ == float::typeid)
{
return dynamic_cast<INumericalOperations<T>^>(gcnew
FloatNumericalAdapter());
}
return nullptr;
}

But it seems there should be a better way than having a bunch of if
statements for each type that is likely to be templatized. Basically we
need a generic T to template T conversion routine.

Dick
 
C

Carl Daniel [VC++ MVP]

Rune said:
Hey,

I am trying to wrap an unmanaged library in managed c++ so that I can
use this library in other .NET languages, such as C#. I've been
successful for the most part this far, but I'm having a hard time
figuring out how to wrap template classes. I'm getting an C3231
compile error when I try to use the generic type as a template type.

Here's an example from the MSDN C3231 compile error site:

template <class T> class A;

generic <class T>
ref class C {
void f() {
A<T> a; // C3231
}
};

Does anyone know how to work around this?

In general, it's simply not possible: Generics are a runtime mechanism
implemented by the CLR. Templates are a compile time mechanism implemented
by the C++ compiler. There's simply no way the CLR can instantiate a
template based on the generic type parameter(s) - only the C++ compiler can
do that.

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top