Frage

I have a template class :

namespace MyApp
{
namespace Interop
{

    template < class A, class B>
    public ref class MyClass
    {
        public:
            MyClass(){}
            ~MyClass(){}

    };

}
}

In a client project this class isn't visible:

class A;
class B;
using namespace MyApp::Interop;

void func()
{
    MyClass< A,B >^ h;
}

I get error C2065: 'MyClass' : undeclared identifier. If MyClass isn't template it is visible in this context.

War es hilfreich?

Lösung

C++ Templates

Class templates have the usual semantics of C++ templates (in other words, you can't you expect CLR clients to "magically" know about and instantiate C++ templates that aren't even available in Assembly Metadata (i.e. Reflection Info)).

The classical C++ solution is going to be explicit instantiation of all the template arguments that you are going to expect this to be used with.

I'll defer to the standard faq items for C++:

CLR Generic Types

In case you wanted a generic CLR type (with CLR semantics, that is) use generic instead of template: Generic Classes (C++/CLI). Example:

// generics_instance_fields1.cpp
// compile with: /clr
// Instance fields on generic classes
using namespace System;

generic <typename ItemType>
ref class MyClass {
// Field of the type ItemType:
public :
   ItemType field1;
   // Constructor using a parameter of the type ItemType:
   MyClass(ItemType p) {
     field1 = p; 
   }
};

int main() {
   // Instantiate an instance with an integer field:
   MyClass<int>^ myObj1 = gcnew MyClass<int>(123);
   Console::WriteLine("Integer field = {0}", myObj1->field1);

   // Instantiate an instance with a double field:
   MyClass<double>^ myObj2 = gcnew MyClass<double>(1.23);
   Console::WriteLine("Double field = {0}", myObj2->field1);

   // Instantiate an instance with a String field:
   MyClass<String^>^ myObj3 = gcnew MyClass<String^>("ABC");
   Console::WriteLine("String field = {0}", myObj3->field1);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top