繁体   English   中英

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

[英]How to pass std::map as a default constructor parameter

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

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

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

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

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

VAL的正确表达式是std::map<std::string, std::string>() 我认为这看起来又长又丑,所以我可能会在类中添加一个公共 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&可能比const map_type更好。

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

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

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

从 C++11 开始,您可以使用聚合初始化

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 上玩这个例子。

首先,切线地,您通过const value传递地图,这是毫无意义的,可能不是您真正想要的。 您可能希望通过const reference传递,这样您就不会复制地图,并确保您的函数不会修改地图。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM