So I was cooking up an answer here and I needed to use C++14's identifier initializer within a lambda capture:
const auto cmp = [ordering = { "dog", "cat", "mouse", "elephant" }](const string& lhs, const string& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); };
And this works fine as long as ordering
is an intializer_list<const char*>
. But for some reason everything falls apart if I make it an intializer_list<string>
:
const auto cmp = [ordering = { "dog"s, "cat"s, "mouse"s, "elephant"s }](const string& lhs, const string& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); };
I would say this was a compiler bug, but I'm seeing an even weirder issue with Visual Studio where everything compares equal when using the intializer_list<string>
, but everything again works fine with an intializer_list<const char*>
, you can copy the test code to http://webcompiler.cloudapp.net to see for yourself.
Is this actually a bug in gcc and Visual Studio or have I done something wrong?
EDIT:
Given code that will use one of these definitions of cmp
:
map<string, int, function<bool(const string&, const string&)>> myMap(cmp);
myMap["cat"s] = 1;
myMap["dog"s] = 2;
myMap["elephant"s] = 3;
myMap["mouse"s] = 4;
myMap["rhino"s] = 5;
for (auto& i : myMap) {
cout << i.first << ' ' << i.second << endl;
}
On Visual Studio and gcc using the intializer_list<const char*>
version correctly generates:
dog 2
cat 1
mouse 4
elephant 3
rhino 5
Using the intializer_list<string>
on http://ideone.com incorrectly generates:
cat 1
dog 2
mouse 4
elephant 5
And using the intializer_list<string>
on Visual Studio incorrectly generates:
cat 5