Can someone explain why the following code won't compile (formatted oddly to make it a touch easier to see the problem):
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 compile error of
error C2440: 'initializing' : cannot convert from 'const wchar_t[4]' to 'System::Windows::Forms::ListViewItem ^'
If the code is broken into two lines as follows, then all is well:
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 one-liner to populate a ListView, why does the compiler have trouble instatiating the ListViewItems in the original code, and how would such a one liner be written?
This quacks loudly like a compiler parser bug. It gets a bit more interesting if you leave the string array initializer empty. Then you 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 the compiler is applying the initializer to the ListViewItem instead of the string array, that's nonsense. It implodes from there.
This isn't going to get fixed any time soon, if at all. You know the fugly workaround. You can post to connect.microsoft.com for a second opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With