如何将 std::map 作为默认构造函数参数传递
我一直无法弄清楚这一点。创建两个演员很容易,但我想了解是否有一种简单的方法可以做到这一点。
如何将 std::map
作为默认参数传递给 ctor,例如
Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)
我尝试过 0
、null
和 NULL
as VAL
,没有任何作用,因为它们都是 int 类型,g++ 抱怨道。这里使用的正确默认值是什么?
或者说这种事情不是一个好主意?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
VAL
的正确表达式是std::map()
。我认为这看起来又长又丑,所以我可能会向类添加一个公共 typedef 成员:顺便说一句,您的意思是最后一个构造函数参数是一个引用吗?
const map_type&
可能比const map_type
更好。The correct expression for
VAL
isstd::map<std::string, std::string>()
. I think that looks long and ugly, so I'd probably add a public typedef member to the class:And by the way, did you mean for the last constructor argument to be a reference?
const map_type&
is probably better than justconst map_type
.您创建一个值初始化的临时值。例如:
(typedef 可能有助于提高代码的可读性)
You create a value-initialized temporary. For example:
(A typedef might help to make this more readable in your code)
从 C++11 开始,您可以使用聚合初始化:
示例:
您可以玩参考 Godbolt 上的示例。
Since C++11 you can use aggregate initialization:
Example:
You can play around with this example at Godbolt.
首先,切线,您通过常量值传递地图,这是毫无意义的,而且可能不是您真正想要的。您可能希望传递常量引用,这样您就不会复制映射,并确保您的函数不会修改映射。
现在,如果您希望默认参数是一个空映射,您可以通过构造它来实现,如下所示:
First, and tangentailly, you are passing the map by const value, which is pointless and probably not what you really want. You probably want to pass by const reference, so that you don't make a copy of the map, and you ensure that your function doesn't modify the map.
Now, if you want your default parameter to be an empty map, you do it by constructing it, like so: