为什么Boost会使用全局函数替代来在“程序选项"中实现自定义验证器? [英] Why Does Boost Use a Global Function Override to Implement Custom Validators in "Program Options"

查看:45
本文介绍了为什么Boost会使用全局函数替代来在“程序选项"中实现自定义验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例显示了一个在全局范围内定义的名为 validate 的函数会重载 boost :: program_options 命名空间中的函数.

This example shows a function named validate defined at global scope overloading a function in the boost::program_options namespace.

使用全局函数重载该设计的合理性是什么?为什么 boost :: program_options 不能实现更严格的设计(例如,覆盖类方法或其他方案)?

What justifies this design using a global function to overload? Why is a more tightly-scoped design not implemented by boost::program_options instead (e.g. overriding a class method, or some other scheme)?

正如下面的评论中所述,我主要担心的是,用户可能惊讶地发现库正在调用其全局函数之一.

As noted in comments below, my main concern is really that a user might be surprised to find that one of their global functions is being called by the library.

应该强调的是,命名为的自由函数非常重要(与全局范围的自由函数相反,请参见

It should be emphasized that namespaced free functions are extremely important (as opposed to global-scope free functions, see this link provided by Chris Drew). Indeed, namespaced, non-class (free) functions are IMO a major benefit of C++.

我的公司正在考虑采用Boost的主要方式,这似乎受到了高度重视.但是,这个特殊的设计决定令我感到担忧.

My company is considering a major adoption of Boost, it seems to be highly regarded. But, this particular design decision has me concerned.

推荐答案

我认为我的主要惊喜是命名空间中定义的函数可以被全局范围内定义的函数重载(隐藏).我要问的是,为什么c ++允许这样做,以及是否有人认为这是一个缺陷,除非您有简要的解释即可. user2141130 2小时前

没有,不能认为是缺陷.

No that cannot be considered a flaw.

该函数将不会被全局范围内定义的函数隐藏.

The function will not be hidden by a function defined at global scope.

这是参数依赖查询(ADL)的目的,并且您一直在使用它!您在这里使用它:

This is what Argument Dependent Lookup (ADL) is for, and you've been using it all around! You use it here:

std::cout << "Hello world!";

ADL非常微妙并且非常普及.许多人直到问自己相同的问题才意识到.自由功能对于扩展点确实非常好.

ADL is pretty subtle and pretty pervasive. Many people don't realize it until they ask themselves the same kind of question you just asked. Free function work really nicely for extension points.

更多: 什么是与参数有关的查找"(又名ADL,或"Koenig查找")?

More: What is "Argument-Dependent Lookup" (aka ADL, or "Koenig Lookup")?

这篇关于为什么Boost会使用全局函数替代来在“程序选项"中实现自定义验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆