Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC refuses list initialisation of parameter

I have the following code:

#include <initializer_list>
#include <utility>

enum class Classification
{
  Unspecified,
  Primary,
  Secondary
};

class ClassificationMap
{
public:
  ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content = {});
};

void foo(ClassificationMap) {}

int main()
{
    foo({{Classification::Unspecified, 42}});
}

Visual Studio 2013 & 2017 and Clang 3.4.1 (and above) both compile the code just fine. From my POV, it should be fine as well. However, GCC 5.1 refuses to compile it, with the following error:

<source>: In function 'int main()':
<source>:22:44: error: could not convert '{{Unspecified, 42}}' from '<brace-enclosed initializer list>' to 'ClassificationMap'
     foo({{Classification::Unspecified, 42}});

[Live example]

(I am passing the correct standard flag (-std=c++11) to both GCC and Clang).

Is there a problem in my code, or is this actually a GCC bug?


Supplemental info: in my real code, the initialiser list is used to initialise an unordered map member of the ClassificationMap class (that's why its type is what it is). I need the code to work in VS2013 & GCC 5.1

like image 904
Angew is no longer proud of SO Avatar asked May 05 '17 12:05

Angew is no longer proud of SO


1 Answers

Here is a good workaround for the issue (abandon default value):

class ClassificationMap
{
public:
    ClassificationMap(std::initializer_list<std::pair<const Classification, int>> content);
    ClassificationMap() : ClassificationMap({}) {}

};

You will have exact behavior you want and it compiles everywhere.

https://godbolt.org/g/WUuMzP

like image 88
Marek R Avatar answered Sep 21 '22 12:09

Marek R