Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

c++ - Boost Program Options Add Options Syntax

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 */)
;

I see that in the header, operator() is overridden, but I'm not sure how that allows this to be syntactically correct.

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...