代码之家  ›  专栏  ›  技术社区  ›  recipriversexclusion

如何将std::map作为默认构造函数参数传递

  •  12
  • recipriversexclusion  · 技术社区  · 15 年前

    一个人怎么能通过 std::map 作为ctor的默认参数,例如。

    Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)
    

    0 , null ,和 NULL VAL ,没有工作,因为它们都是int类型,g++抱怨道。这里使用的正确默认值是什么?

    或者这种事情不是个好主意?

    4 回复  |  直到 15 年前
        1
  •  27
  •   aschepler    15 年前

    正确的表达式 VAL std::map<std::string, std::string>()

    class Foo {
    public:
      typedef std::map<std::string, std::string> map_type;
      Foo( int arg1, int arg2, const map_type = map_type() );
      // ...
    };
    

    顺便问一下,你是说最后一个构造函数参数是引用吗? const map_type& const map_type .

        2
  •  6
  •   James McNellis    15 年前

    创建一个临时初始化的值。例如:

    Foo::Foo(int arg1,
             int arg2,
             const std::map<std::string, std::string>& the_map =
                 std::map<std::string, std::string>())
    {
    }
    

        3
  •  4
  •   Phidelux    8 年前

    因为C++ 11你可以使用 aggregate initialization :

    void foo(std::map<std::string, std::string> myMap = {});
    

    #include <iostream>
    #include <map>
    #include <string>
    
    void foo(std::map<std::string, std::string> myMap = {})
    {
        for(auto it = std::begin(myMap); it != std::end(myMap); ++it)
            std::cout << it->first << " : " << it->second << '\n';
    }
    
    int main(int, char*[])
    {
        const std::map<std::string, std::string> animalKids = {
            { "antelope", "calf" }, { "ant", "antling" },
            { "baboon", "infant" }, { "bear", "cub" },
            { "bee", "larva" }, { "cat", "kitten" }
        };
    
        foo();
        foo(animalKids);
    
        return 0;
    }
    
        4
  •  2
  •   John Dibling    15 年前

    首先,相切地,你正在传递地图 常量值 常量引用 ,这样就不会复制地图,并且确保函数不会修改地图。

    现在,如果希望默认参数为空映射,可以通过构造它来实现,如下所示:

    Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string>& = std::map<std::string, std::string>())