简体   繁体   English

boost program_options如何工作?

[英]How does boost program_options work?

The weird thing to me is, that boost's options_description uses multi-line code without backslash or semicolon or comma. 对我来说奇怪的是,boost的options_description使用没有反斜杠或分号或逗号的多行代码。 I did a little research, but found nothing. 我做了一点研究,但一无所获。

(Code taken from official boost's tutorial ): (代码来自官方的boost教程 ):

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 it implemented? 它是如何实现的? Is it a macro? 这是一个宏吗?

It's a bit of a strange syntax in C++ but if you're familiar with JS (for example), you might be aware of the concept of method chaining . 这在C ++中有点奇怪的语法,但是如果你熟悉JS(例如),你可能会意识到方法链的概念。 This is a bit like that. 这有点像。

add_options() returns an object with operator() defined. add_options()返回一个定义了operator()的对象。 The second line calls operator() on the object returned by the first line. 第二行在第一行返回的对象上调用operator() The method returns a reference to the original object, so you can keep calling operator() many times in a row. 该方法返回对原始对象的引用,因此您可以连续多次调用operator()

Here's 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 pointed out by gbjbaanb in the comments, this is actually quite similar to how chaining of assignments a = b = c = 0 works for classes. 正如gbjbaanb在评论中指出的那样,这实际上非常类似于赋值a = b = c = 0链接a = b = c = 0适用于类。 It is also similar to the behaviour that is pretty much taken for granted when using ostream::operator<< : you expect to be able to do std::cout << "string 1" << "string 2" << "string 3" . 它也类似于使用ostream::operator<<时非常理所当然的行为:你希望能够做std::cout << "string 1" << "string 2" << "string 3"

The add_options() method returns object that implements the "()" operator and the () operator in turn returns the same object. add_options()方法返回实现“()”运算符的对象,而()运算符依次返回相同的对象。 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;
}

This is the way it works. 这是它的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM