Boost程序选项添加选项语法 [英] Boost Program Options Add Options Syntax
问题描述
我正在编写一个使用Boost的程序选项库的程序,并且注意到以下语法自从我看到以来一直困扰着我:
I am writing a program that uses Boost's Program Options library and I noticed the following syntax that has haunted me since I saw it:
desc.add_options()
("help","produce help message")
( /* other flag, value, description pairs here */)
;
我看到在标头中,operator()被覆盖了,但是我不确定如何使它在语法上正确.
I see that in the header, operator() is overridden, but I'm not sure how that allows this to be syntactically correct.
第二,与仅多次调用add_options()相比,此语法有什么优势(除了炫耀您可以像这样操作语法的事实)?
Secondly, is there any advantage to this syntax, compared with just calling add_options() multiple times (besides showing off the fact that you can manipulate syntax like this)?
推荐答案
add_options
成员函数返回类型为options_description_easy_init
的对象.后者的operator()
重载以返回对自身的引用.这样,您就可以按照代码段中所示的方式链接呼叫.
The add_options
member function returns an object of type options_description_easy_init
. The latter has operator()
overloaded to return a reference to itself. This allows you to chain the calls as you've shown in the snippet.
多次链接调用和调用add_options
之间的区别在于,在前一种情况下,创建了options_description_easy_init
的单个实例,并且每次在其上调用operator()
时,它都会向所有者添加选项( options_description
).如果您多次呼叫add_options
,则每次呼叫都会创建一个options_description_easy_init
的新实例.
The difference between chaining the calls and calling add_options
several times is that in the former case a single instance of options_description_easy_init
is created and each time you invoke operator()
on it, it adds the options to the owner (options_description
). If you were to call add_options
multiple times each call would create a new instance of options_description_easy_init
.
这篇关于Boost程序选项添加选项语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!