简体   繁体   English

默认参数的默认构造

[英]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. 假设参数是std::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. 现在,如果Key和/或Value的名称很长(可能是模板化的),则函数声明会很长。 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. 现在,我知道这不是使用关键字auto ,而只是为了解释这个概念:我不想因为已经写下一个简单的默认构造的默认值而将已经很长的函数声明的长度加倍元件。 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. 注意:是的,我可以typedef映射类型并使用短名称。 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. 注意2:是的,我也可以重载该函数,以便它的一个版本不带参数,而另一个版本则带参数。 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 = {});

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

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