您的位置:首页 > 编程语言 > C语言/C++

(原創) 我的VS2008之旅[1] : STL/CLR (.NET) (C++/CLI) (STL) (C/C++)

2007-08-08 19:16 525 查看
Abstract
VS2008最讓我有興趣的,首推LINQ,其次就是STL/CLR和Lambda了,LINQ在博客園討論的人已經很多,所以我將VS2008之旅首站駛往STL/CLR。

Introduction
我是先學C#,然後才學C++。C++讓我最癡迷的首推STL,其次則為泛型template。C++/CLI在VS2005中,template保留了大部分ISO C++的功能,如template template parameter,partial specialization,nontype template parameter等,使的大部分泛型技術如Policy-based Design,Traits等得以實現。而STL在C++/CLI雖然可用,但僅限於native type,而managed type則無福消受。MS曾宣稱要將STL在VS2005移植到.net,但可惜跳票了。在千呼萬喚中,總算在VS2008發表了STL/CLR,這是STL移植到.net的版本,可以使用managed type。

STL/CLR
使用STL/CLR的方法很簡單
1.referece Microsoft.VisualC.STLCLR.dll
2.include new header for STL/CLR
如vector : #include <cliext/vector>
泛型算法:#include <cliext/algorithm>
3.namespace從std改成cliext

Example
一個很簡單的需求,List<int>包含了1,2,1,3四筆數據,希望將所有的1用4取代,也就是希望結果為4,2,4,3。

ISO C++

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

4
2
4
3

16行

vector<int> ivec;

是STL的vector container,類似.net的List<T>。

22行

replace(ivec.begin(), ivec.end(), 1, 4);

為STL提供的『泛型算法』,將vector中所有的1替換為4。

C++/CLI 2

#include "stdafx.h"
#include <cliext/vector> // STL/CLR vector
#include <cliext/algorithm> // STL/CLR algorithm

using namespace System;
using namespace cliext; // STL/CLR namespace

4
2
4
3

10、11行

#include <cliext/vector> // STL/CLR vector
#include <cliext/algorithm> // STL/CLR algorithm

為STL/CLR另外擴充的header。

14行

using namespace cliext; // STL/CLR namespace

將原本namespace從std改成cliext。

17行

vector<int> ivec;

一樣可以使用STL的vector。

24行

replace(ivec.begin(), ivec.end(), 1, 4);

感動吧!!一樣可以使用STL『泛型算法』:replace()。

Conclusion
當然這個範例使用了vector<int>,並不能真正看出STL/CLR的威力,STL/CLR真正的強大是用在managed type上。本範例主要是展現透過reference新的assembly和include new header files,new namespace,即可簡單的使用.net平台的STL/CLR,除了讓你更簡單的將以前使用STL的代碼移植到.net,也可繼續使用STL這個強大的泛型框架。

Remark
由於VS2008尚未正式推出,目前僅能用Orcas Beta2加以測試,測試中發現若乖乖的在Project中加入

Microsoft.VisualC.STLCLR

這個reference,並無法compile成功,會出現

could not find assembly 'Microsoft.VisualC.STLCLR.dll': please specify the assembly search path using /AI or by setting the LIBPATH environment variable

錯誤訊息,我的解決方式是將

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\Microsoft.VisualC.STLCLR.dll

複製到自己的project目錄下,然後reference這個assembly,如此則可正常執行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐