9

Consider simple code snippet

#include <map>
#include <string>


struct Foo
{
    Foo(const std::map<std::string, int> & bar = std::map<std::string, int>())
        :bar(bar)
    { }

    std::map<std::string, int> bar;
};

int main(int argc, char ** argv)
{
    return 0;
}

When I compile it like this: clang++ -o foo foo.cpp I face errors:

foo.cpp:7:73: error: expected ')'
    Foo(const std::map<std::string, int> bar = std::map<std::string, int>())
                                                                        ^
foo.cpp:7:8: note: to match this '('
    Foo(const std::map<std::string, int> bar = std::map<std::string, int>())
       ^
foo.cpp:7:68: error: expected '>'
    Foo(const std::map<std::string, int> bar = std::map<std::string, int>())
                                                                   ^

Same behaviour for clang 3.2 and clang 3.3.

So I am wondering if I missing something or is it a bug? GCC does not complain.

8
  • Can you try {} instead of ()?
    – stefan
    Commented May 22, 2014 at 7:53
  • Yes it seems to be a bug in your versions of clang. Tested with clang version 3.5.0 (trunk 203891) and it works fine. Commented May 22, 2014 at 7:54
  • It compiles in glang++ 3.5 (pre-3.5 from last week or so) and gcc 4.8.2, as well as clang 2.9 and g++ 4.6.3. Which is all the compilers I have on my current machine... Commented May 22, 2014 at 7:55
  • @stefan same errors. It looks like parser error so I doubt that changing () to {} had any chance to fix it :)
    – GreenScape
    Commented May 22, 2014 at 7:55
  • If you can't upgrade clang to a later version, then you can work around it by making a default constructor (i.e. one without any arguments). Commented May 22, 2014 at 7:55

1 Answer 1

2

It's a fallacy in the C++ grammar that will surprise you. I'm unsure if this has been rectified or cleared out, see below.

All major compilers accept it though, including newer versions of Clang.

A list of references pertaining to the issue:

3
  • So, being a standard-paranoid type, I am wondering. Is is piece of code is considered t be vaild. If it's not, will it be fixed in next C++ standard so that it become valid?
    – GreenScape
    Commented May 22, 2014 at 8:08
  • @GreenScape: I can't tell from the working group issue comments. The safe path is to use a typedef, IMHO. In any case, that won't be bad practice, even if you just do using map_string_int = std::map<std::string, int>;. It's still mind-boggling to me that the grammar forbids this.
    – rubenvb
    Commented May 22, 2014 at 8:11
  • @rubenvb: Yeah, from the "user's" perspective this seems unnatural. Thank you for help!
    – GreenScape
    Commented May 22, 2014 at 8:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.