How to pass std::map as a default constructor parameter
The correct expression for VAL
is std::map<std::string, std::string>()
. I think that looks long and ugly, so I'd probably add a public typedef member to the class:
class Foo {
public:
typedef std::map<std::string, std::string> map_type;
Foo( int arg1, int arg2, const map_type = map_type() );
// ...
};
And by the way, did you mean for the last constructor argument to be a reference? const map_type&
is probably better than just const map_type
.
You create a value-initialized temporary. For example:
Foo::Foo(int arg1,
int arg2,
const std::map<std::string, std::string>& the_map =
std::map<std::string, std::string>())
{
}
(A typedef might help to make this more readable in your code)
Since C++11 you can use aggregate initialization:
void foo(std::map<std::string, std::string> myMap = {});
Example:
#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;
}
You can play around with this example at Godbolt.