Jac*_* L. 7 c++ boost boost-program-options
对我来说奇怪的是,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") ;
Run Code Online (Sandbox Code Playgroud)
它是如何实现的?这是一个宏吗?
Tom*_*ech 18
这在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;
}
Run Code Online (Sandbox Code Playgroud)
正如gbjbaanb在评论中所指出的,这实际上与分配的链接如何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;
}
Run Code Online (Sandbox Code Playgroud)
这是它的工作方式.