我有一个模板类:
namespace MyApp
{
namespace Interop
{
template < class A, class B>
public ref class MyClass
{
public:
MyClass(){}
~MyClass(){}
};
}
}
在客户端项目中,此类不可见:
class A;
class B;
using namespace MyApp::Interop;
void func()
{
MyClass< A,B >^ h;
}
我收到错误C2065:'MyClass':未声明的标识符。 如果MyClass不是模板,则在此上下文中可见。
答案 0 :(得分:1)
类模板具有C ++模板的通常语义(换句话说,您不能指望CLR客户端“神奇地”了解并实例化在汇编元数据中甚至不可用的C ++模板(即反射信息))
经典的C ++解决方案将是您希望与之一起使用的所有模板参数的显式实例化。
我将遵循C ++的标准faq项目:
如果您想要一个通用的CLR类型(使用CLR语义),请使用generic
而不是template
: Generic Classes (C++/CLI) 。例如:
// 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);
}