简体   繁体   中英

Default construction for default parameters

Premise: I'm lazy. And I don't like long lines.

Suppose you have a function that takes one parameter, and you want to give a default value for that parameter. Let's say that parameter is a std::map , and the default is just an empty map. The way to do it would be

void foo (std::map<Key,Value> the_map = std::map<Key,Value>());

Now, if the name of Key and/or Value is long (perhaps templated), the function declaration becomes long. It would be nice to have a way to write something like

void foo (std::map<Key,Value> the_map = auto);

Now, I know that's not the use of the keyword auto , but it was only to explain the concept: I don't want to double the length of an already long function declaration just because of having to write down a simple default-constructed default element. I just want to tell the compiler "look, build a default one there". Is there a way to do this? Also, does anybody feel this need too?

Note: yes, I could typedef the map type and use the short name. But I would like a different way. Note 2: yes, I could also overload the function, so that one version of it takes no arguments and the other does. But I would like a different way.

I guess what I'm looking for is a "default default parameter"...

您可以将{}用作初始化程序子句 ,这将对参数进行值初始化。

void foo(std::map<K, V> the_map = {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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