C ++原生于C ++ / CX:如何将std :: vector转换为IVector?

时间:2013-04-12 15:13:38

标签: c++ generics struct stdvector

我很擅长用C ++编程。多年来我做过一些C#,但我不会说我精通它。我正在尝试将一些代码从本机c ++更改为C ++ / CX并继续遇到大量编译器错误,特别是与向量有关。我一直在阅读MSDN - Collections (C++/CX)并且收集到我需要使用IVector。

我在另一个头文件中定义了一个结构:

typedef struct myStruct{
 float p;
 double x;
 double y;
 uint id;
}

我使用了这个结构的向量作为方法声明中的参数:

void ProcessStruct (std::vector<myStruct> myStructs){}

将其转换为IVector时,如下所示:

void ProcessStruct (Windows::Foundation::Collections::IVector<myStruct>^ myStructs){}

我总是得到编译器错误C3225:“'arg'的泛型类型参数不能是'type',它必须是值类型或句柄类型”。我尝试使用IVector<myStruct^>^代替,但后来我最终得到了C3699:“operator':不能在类型'type'上使用这个间接”

所以我猜我唯一的选择是创建一个通用的,但在这里我对我实际应该做的事情感到非常困惑。如何获取结构并将其转换为通用结构?什么是std :: vector做那个IVector不能?

1 个答案:

答案 0 :(得分:1)

首先,你需要使用Platform :: Collections :: Vector而不是std :: vector。它们基本上都是一样的,因为它们都像向量一样,但是Platform :: Collections :: Vector是一个WRT对象,这就是为什么我们使用^(hat指针)来处理它们。

我用它像:

public ref class Something{
public:
    property Windows::Foundation::Collections::IVector<int>^ num{
        void set(Windows::Foundation::Collections::IVector<int>^ e){
            NUM = static_cast<Platform::Collections::Vector>(e);
        };
        Windows::Foundation::Collections::IVector<int>^ get(){
            return NUM;
        };
    };

private:
    Platform::Collections::Vector<int>^ NUM;
};

在某种意义上,您使用IVector作为属性(因为属性可以是公共成员),然后将其转换为c ++ / cx Vector。稍后当您需要它时,使用IVector作为媒介来返回Vector。

另请注意,set函数的参数是IVector,get函数也是IVector类型。

一些代码可以帮助:)

void Something::SomeFunction(){
num = ref new Vector<int>;  //make num point to a new Vector<int>

num->Append(5);             //Take the number 5 cast it from IVector to Vector
                            //and store it in NUM. (The cast happens due to
                            //the code in the IVector property we made)

int TempNum = 7 + num->GetAt(0);    //Use num to get the first element of NUM and 
                                    //add 7 to it. (It's now 10, I mean 12)


num->InsertAt(0, T);                //Take T (12) and replace it with the first
                                    //element in NUM.
};

请记住,当我们对num执行某些操作时,会将其转换为NUM。这就是为什么有一个接口,它们帮助我们在Java,C#等之间使用Vector(或任何其他东西,比如String或Map)。