【问题标题】:How to pass std::map as a default constructor parameter如何将 std::map 作为默认构造函数参数传递
【发布时间】:2011-05-06 22:32:45
【问题描述】:

我无法弄清楚这一点。创建两个 ctor 很容易,但我想了解是否有简单的方法可以做到这一点。

如何将std::map 作为默认参数传递给 ctor,例如

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

我试过0nullNULL 作为VAL,没有任何工作,因为它们都是 int 类型,g++ 抱怨。此处使用的正确默认值是什么?

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

【问题讨论】:

    标签: c++ constructor default-value stdmap


    【解决方案1】:

    VAL 的正确表达式是 std::map&lt;std::string, std::string&gt;()。我认为这看起来又长又丑,所以我可能会在类中添加一个公共 typedef 成员:

    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&amp; 可能比 const map_type 更好。

    【讨论】:

    • +1 是唯一将默认值放在 declaration 而不是 definition 的解决方案。
    【解决方案2】:

    您创建了一个值初始化的临时对象。例如:

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

    (typedef 可能有助于使代码在您的代码中更具可读性)

    【讨论】:

      【解决方案3】:

      从 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::cbegin(myMap); it != std::cend(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;
      }
      

      您可以在Godbolt 玩这个示例。

      【讨论】:

        【解决方案4】:

        首先,切题的是,您通过 const 值 传递地图,这是没有意义的,可能不是您真正想要的。您可能希望通过 const 引用,这样您就不会复制地图,并确保您的函数不会修改地图。

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

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

        【讨论】:

          猜你喜欢
          • 2013-08-12
          • 2012-11-14
          • 2021-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-10
          • 2019-11-28
          • 1970-01-01
          相关资源
          最近更新 更多