[英]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.