原生类型和泛型
我想创建一个本机数组并访问它的托管代码。我不想将代码重新编写为不同类型(int
、long
、float
、double
)因此尝试使用泛型。
typedef int IND;
generic <typename T>
public ref class ntvarray
{
void *pnt;
IND sz;
public:
ntvarray(IND length)
{
sz = sizeof(T);
pnt = ::operator new(length*sz);
}
~ntvarray()
{
::operator delete(pnt);
}
void* pointer()
{
return pnt;
}
T getitem (IND index)
{
//c3229
return ((T*)pnt)[index];
}
void setitem (IND index, T value)
{
//c3229
((T*)pnt)[index] = value;
}
};
我收到错误并且我知道此错误的原因,
错误 C3229:
'T *'
:不允许对泛型类型参数进行间接引用
但是有没有办法使用泛型来做到这一点?除了使用泛型之外,还有其他方法可以做到这一点吗?
I want to create a native array and access it managed code. I don't want to re write code to different types, (int
, long
, float
, double
) therefore tried using generics.
typedef int IND;
generic <typename T>
public ref class ntvarray
{
void *pnt;
IND sz;
public:
ntvarray(IND length)
{
sz = sizeof(T);
pnt = ::operator new(length*sz);
}
~ntvarray()
{
::operator delete(pnt);
}
void* pointer()
{
return pnt;
}
T getitem (IND index)
{
//c3229
return ((T*)pnt)[index];
}
void setitem (IND index, T value)
{
//c3229
((T*)pnt)[index] = value;
}
};
I am getting the error and I know the reason for this error,
error C3229:
'T *'
: indirections on a generic type parameter are not allowed
However is there a way to do this using generics? Any other way to do this, may be something else other than using generics?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,你不能使用泛型来做到这一点。但您可以使用模板。这避免了代码重复,您的问题强调了这一点,但不允许像泛型那样进行运行时实例化。
No, you can't do this using generics. But you can use templates. This avoids the code duplication, which your question emphasizes, but won't allow run-time instantiation like generics would.