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

rec*_*ion 13 c++ constructor stdmap default-value

我无法弄清楚这一点.创建两个ctors很容易,但我想知道是否有一个简单的方法来做到这一点.

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

Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)
Run Code Online (Sandbox Code Playgroud)

我试过0,nullNULL作为VAL,没有工作,因为他们都是int类型,G ++抱怨的.这里使用的默认值是什么?

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

asc*_*ler 27

正确的表达方式VALstd::map<std::string, std::string>().我认为这看起来很长很难看,所以我可能会在类中添加一个public typedef成员:

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

顺便说一下,你的意思是最后一个构造函数参数是一个引用吗? const map_type&可能比仅仅更好const map_type.

  • +1是唯一的解决方案,它将默认值放在*声明*而不是*definition*中. (6认同)

Jam*_*lis 6

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

Foo::Foo(int arg1,
         int arg2,
         const std::map<std::string, std::string>& the_map =
             std::map<std::string, std::string>())
{
}
Run Code Online (Sandbox Code Playgroud)

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


Phi*_*lux 6

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

void foo(std::map<std::string, std::string> myMap = {});
Run Code Online (Sandbox Code Playgroud)

例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

你可以在Godbolt 上玩这个例子。