C++/CLI的泛型

111 views 十一月 13, 06 by Timothy

泛型,其实在C++里面已经不是一个新概念了。他允许C++程序员参数化类型,把类型作为参数抽象出来,更好的实现代码的复用,并且使你的程序更加简洁,不用去为同一个函数重载多个不同参数类型的版本。在.NET 2.0中也加入了对泛型的支持。而随着STL也被集成到.NET中来,成为STL.NET,我们在采用C++/CLI开发的时候,就有了更多的选择。利用.NET框架所提供的数据集合System::Collection,或者是使用泛型System::Collection::Generic,还可以使用STL.NET。
Stanley B. Lippman在文章STL.NET Primer中提到,STL.NET被经过重新设计,集成到.NET中来,结合了泛型和模板的机制,看看他对STL.NET的评价:In my judgment, when combined with the
revised C++/CLI dynamic programming support, this coming version of Visual C++ is
simply the most satisfying language in which to program. I think STL.NET is a very exciting
library addition, and I hope that after you finish this series of articles you will agree with
me.
泛型与模板的应用,在C++/CLI中,会变得更有乐趣。
下面,是在C++/CLI中使用泛型、模板的一些例子。这里没有采用STL.NET,关于STL.NET的介绍,可以参考Lippman的文章:http://msdn2.microsoft.com/en-us/library/ms379600(VS.80).aspx

//这是我们自己实现的,用来模拟堆栈结构的模板类
template
ref class MyStack
{
private:
ArrayList ^ mList;
public:
MyStack()
{
mList= gcnew ArrayList();
}

void push(T const & type)
{
mList->Add(type);
}

int pop(T &value)
{
if(mList->Count > 0)
{
value=*reinterpret_cast( mList[mList->Count - 1]);
mList->RemoveAt(mList->Count – 1);
return true;
}
else
{
return false;
}
}
};

int main(array ^args)
{
//实例化这个模板类
MyStack ^ mystack = gcnew MyStack ();
mystack->push(12);
mystack->push(13);

int a,b;
mystack->pop(a);
mystack->pop(b);
Console::WriteLine("a is:{0} and b is:{1}",a,b);

//.NET 2.0提供的泛型支持,为我们封装好了一个Stack
System::Collections::Generic::Stack ^ stack =
gcnew System::Collections::Generic::Stack ();
stack->Push("World");
stack->Push("Hello");

Console::WriteLine("{0} {1}",stack->Pop(),stack->Pop());

return 0;
}

运行结果如图:

分享到:

声明: 此Blog中的文章和随笔仅代表作者在某一特定时间内的观点和结论,对其完全的正确不做任何担保或假设
本站文章均采用 知识共享署名-相同方式共享3.0 协议进行授权,除非注明,本站文章均为原创,转载请注明转自 Timothy's Space 并应以链接形式标明本文地址!

你可能也对下列文章感兴趣

  • 没有相关文章!

<

这篇文章还没有人评论... 赶快来抢沙发吧!.


Leave a Reply

 您已输入0

(Ctrl+Enter)