Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI array initializer compilation error

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?

like image 250
Waldo Avatar asked Mar 11 '11 22:03

Waldo


1 Answers

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.

like image 79
Hans Passant Avatar answered Sep 16 '22 18:09

Hans Passant