I haven't been able to figure this out. It's easy to create two ctors but I wanted to learn if there's an easy way to do this.
How can one pass a std::map
as the default parameter to a ctor, e.g.
Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)
I've tried 0
, null
, and NULL
as VAL
, none of the work because they are all of type int, g++ complains. What is the correct default to use here?
Or is this kind of thing not a good idea?
The default constructor is not required. Certain container class member function signatures specify the default constructor as a default argument. T() must be a well-defined expression ...
Default Constructor – A constructor that accepts no parameter is called Default Constructor. It is not necessary to have a constructor block in your class definition. If you don't explicitly write a constructor, the compiler automatically inserts one for you.
By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.
Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With