C ++ / CLI array initializer compilation error

Can someone explain why the following code will not compile (formatted weirdly to make it easier to view):

ListView ^ listview = gcnew ListView(); listview->Items->AddRange( gcnew array<ListViewItem^> { gcnew ListViewItem( gcnew array<String^> { L"red", L"fish" } ), gcnew ListViewItem( gcnew array<String^> { L"green", L"eggs" } ) }); 

This gives a compilation error

error C2440: 'initializing': cannot be converted from 'const wchar_t [4]' to 'System :: Windows :: Forms :: ListViewItem ^'

If the code is split into two lines as follows, then everything is fine:

 ListView^ listview = gcnew ListView(); ListViewItem^ lvi1 = gcnew ListViewItem( gcnew array<String^> { L"red", L"fish" } ); ListViewItem^ lvi2 = gcnew ListViewItem( gcnew array<String^> { L"green", L"eggs" } ); listview->Items->AddRange( gcnew array<ListViewItem^> { lvi1, lvi2 }); 

Ignoring why someone wants to make a monolithic single-line layer to populate the ListView, why does the compiler have problems initializing ListViewItems in the source code, and how will such one liner be written?

+6
compiler-construction c ++ - cli
source share
1 answer

This jokes loudly, like a compiler parser error. This gets a little more interesting if you leave the string array initializer empty. Then you will get this description in the output window:

 1>c:\projects\cpptemp26\Form1.h(77) : error C2552: '$S4' : non-aggregates cannot be initialized with initializer list 1> 'System::Windows::Forms::ListViewItem ^' is not an array or class : Types which are not array or class types are not aggregate 1>c:\projects\cpptemp26\Form1.h(78) : error C2440: 'initializing' : cannot convert from 'const wchar_t [6]' to 'System::Windows::Forms::ListViewItem ^' 1> Reason: cannot convert from 'const wchar_t *' to 'System::Windows::Forms::ListViewItem ^' 1> No user-defined-conversion operator available, or 1> Cannot convert an unmanaged type to a managed type 

Note the message "ListViemItem ^ is not an array or class." This strongly suggests that the compiler applies the initializer to the ListViewItem instead of an array of strings, this nonsense. He pushes away from there.

This will not be fixed soon, if at all. You know this is an ugly workaround. You can send a message to connect.microsoft.com to get a second opinion.

+4
source share

All Articles