【发布时间】:2010-04-02 19:11:06
【问题描述】:
我想创建一个通用的 IEnumerable 实现,以便更轻松地包装一些本机 C++ 类。当我尝试使用模板参数作为 IEnumerable 的参数来创建实现时,出现错误。
这是我想出的一个简单版本,可以证明我的问题:
ref class A {};
template<class B>
ref class Test : public System::Collections::Generic::IEnumerable<B^> // error C3225...
{};
void test()
{
Test<A> ^a = gcnew Test<A>();
}
在指示的行上,我收到此错误:
错误 C3225:“T”的泛型类型参数不能是“B ^”,它必须是值类型或引用类型的句柄
如果我使用不同的父类,我看不到问题:
template<class P>
ref class Parent {};
ref class A {};
template<class B>
ref class Test : public Parent<B^> // no problem here
{};
void test()
{
Test<A> ^a = gcnew Test<A>();
}
我可以通过向实现类型添加另一个模板参数来解决它:
ref class A {};
template<class B, class Enumerable>
ref class Test : public Enumerable
{};
void test()
{
using namespace System::Collections::Generic;
Test<A, IEnumerable<A^>> ^a = gcnew Test<A, IEnumerable<A^>>();
}
但这对我来说似乎很乱。另外,我只是想了解这里发生了什么 - 为什么第一种方法不起作用?
【问题讨论】:
标签: templates generics c++-cli