Dot-Net

同時使用託管數組和 std:array 不兼容

  • April 14, 2014

我的 C++/CLI 程式碼使用這樣的數組(例如):

array<String^>^ GetColNames() { 
   vector<string> vec = impl->getColNames();
   array<String^>^ arr = gcnew array<String^>(vec.size());

   for (int i = 0; i < vec.size(); i++) { 
       arr[i] = strConvert(vec[i]); 
   }
   return arr; 
}

在我將庫“數組”添加到項目之前,它的編譯正常:

#include <array>

然後我不知道如何使用託管 CLI 數組,因為編譯器認為所有聲明的數組都是std::array.

錯誤範例:

array<String^>^ arr
//           ^ Error here: "too few arguments for class template "std::array""

gcnew array<String^>(vec.size())
//    ^ Error: "Expected a type specifier"

如何解決這個問題?我嘗試using namespace std從該文件中刪除,但沒有任何區別。我應該從項目的所有其他 C++ 文件中刪除它嗎?

顯然你using namespace std;在某個地方有一個範圍。如果找不到它,請注意它在 .h 文件中的使用情況。

您可以解決歧義,像數組這樣的 C++/CLI 擴展關鍵字在cli命名空間中。這編譯得很好:

#include "stdafx.h"
#include <array>

using namespace std;         // <=== Uh-oh
using namespace System;

int main(cli::array<System::String ^> ^args)
{
   auto arr = gcnew cli::array<String^>(42);
   return 0;
}

引用自:https://stackoverflow.com/questions/23062179