繁体   English   中英

boost program_options如何工作?

[英]How does boost program_options work?

对我来说奇怪的是,boost的options_description使用没有反斜杠或分号或逗号的多行代码。 我做了一点研究,但一无所获。

(代码来自官方的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") ;

它是如何实现的? 这是一个宏吗?

这在C ++中有点奇怪的语法,但是如果你熟悉JS(例如),你可能会意识到方法链的概念。 这有点像。

add_options()返回一个定义了operator()的对象。 第二行在第一行返回的对象上调用operator() 该方法返回对原始对象的引用,因此您可以连续多次调用operator()

这是它的工作原理的简化版本:

#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;
}

正如gbjbaanb在评论中指出的那样,这实际上非常类似于赋值a = b = c = 0链接a = b = c = 0适用于类。 它也类似于使用ostream::operator<<时非常理所当然的行为:你希望能够做std::cout << "string 1" << "string 2" << "string 3"

add_options()方法返回实现“()”运算符的对象,而()运算符依次返回相同的对象。 请参阅以下代码:

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;
}

这是它的工作方式。

暂无
暂无

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

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