How does boost_options work?

The weird thing for me is that boost options_description uses multi-line code without a backslash or semicolon or semicolon. I did a little research, but found nothing.

(Code taken from the official performance book ):

int opt; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("optimization" , po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I ", po::value< vector<string> >() , "include path") ("input-file ", po::value< vector<string> >() , "input file") ; 

How is this implemented? Is this a macro?

+6
source share
2 answers

This is a bit of a strange syntax in C ++, but if you are familiar with JS (for example), you may be aware of the concept of a method chain. It is a bit like this.

add_options() returns an object with operator() . The second line calls operator() object returned by the first line. The method returns a reference to the original object, so you can continue to call operator() many times in a row.

Here is a simplified version of how it works:

 #include <iostream> class Example { public: Example & operator()(std::string arg) { std::cout << "added option: " << arg << "\n"; return *this; } Example & add_options() { return *this; } }; int main() { Example desc; desc.add_options() ("first") ("second") ("third"); return 0; } 

As noted in gbjbaanb's comments, this is actually very similar to how the assignment chain a = b = c = 0 works for classes. It also looks like behavior that is often taken for granted when using ostream::operator<< : you expect to be able to do std::cout << "string 1" << "string 2" << "string 3" .

+17
source

The add_options () method returns an object that implements the "()" operator, and the () operator in turn returns the same object. See the following code:

 class Example { public: Example operator()(string arg) { cout << arg << endl; return Example(); } Example func(string arg) { operator()(arg); } }; int main() { Example ex; ex.func("Line one") ("Line two") ("Line three"); return 0; } 

And so it works.

+7
source

Source: https://habr.com/ru/post/973027/


All Articles