如何将std :: map作为c ++类函数中的默认构造函数参数传递

时间:2013-08-10 09:45:52

标签: c++ clang stdmap

尝试在Ubuntu 12.04上的clang-3.3和clang-3.0中使用std::map时遇到问题:

#include <iostream>
#include <map>
#include <string>

class A
{
public:
#if 0 //clang compiles ok
    typedef std::map<std::string,std::string> MapKeyValue_t;
    void PrintMap(const MapKeyValue_t &my_map 
        = MapKeyValue_t())
#else // clang compiles fail
    void PrintMap(const std::map<std::string,std::string> &my_map 
    = std::map<std::string,std::string>())
#endif
{
    std::map<std::string,std::string>::const_iterator it;
    for (it = my_map.begin(); it != my_map.end(); it++)
    {
        std::cout << it->first << " " << it->second << std::endl;
    }
}
};

int main()
{
    A a;
    a.PrintMap();
    return 0;
}

但是,虽然代码在g++clang中编译,但我仍然将这些错误作为输出:

test.cpp:14:36: error: expected ')'
        = std::map<std::string,std::string>())
                                          ^
test.cpp:13:15: note: to match this '('
        void PrintMap(const std::map<std::string,std::string> &my_map 
                     ^
test.cpp:14:24: error: expected '>'
        = std::map<std::string,std::string>())
                              ^
test.cpp:28:13: error: too few arguments to function call, expected 2, have 0
        a.PrintMap();
        ~~~~~~~~~~ ^
test.cpp:13:2: note: 'PrintMap' declared here
        void PrintMap(const std::map<std::string,std::string> &my_map 
        ^
3 errors generated.

我能找到的最符合我问题的是这个话题:How to pass std::map as a default constructor parameter

但是,我不知道出了什么问题。希望有人可以对此有所了解。

更新

void PrintMap(const std::map<std::string,std::string> &my_map 
        = (std::map<std::string,std::string>()))

没问题。感谢。

2 个答案:

答案 0 :(得分:1)

我在vs2012中成功编译并运行它 所以我认为这是编译器问题。

答案 1 :(得分:1)

其他海报是正确的,我认为这是Bug 13657的一个实例,应该在Clang 3.4中修复。

正如错误报告和从那里链接的C++ Standard Core Language Active Issues页面(正如您在更新中提到的那样)中提到的,您可以通过将括号添加到默认值来解决此问题,如下所示:

void PrintMap(const std::map<std::string,std::string> &my_map 
    = (std::map<std::string,std::string>()))