Дополнительные возможности программы Добавить параметры Синтаксис
Я пишу программу, которая использует библиотеку опций программы Boost, и я заметил следующий синтаксис, который преследовал меня с тех пор, как я увидел это:
desc.add_options()
("help","produce help message")
( /* other flag, value, description pairs here */)
;
Я вижу, что в заголовке оператор() переопределен, но я не уверен, как это может быть синтаксически корректным.
Во-вторых, есть ли какое-либо преимущество для этого синтаксиса по сравнению с просто вызовом add_options() несколько раз (помимо того, что вы можете манипулировать синтаксисом, подобным этому)?
Ответы
Ответ 1
Функция-член add_options
возвращает объект типа options_description_easy_init
. Последний имеет operator()
, перегруженный, чтобы вернуть ссылку на себя. Это позволяет вам цепочки вызовов, как показано в фрагменте.
Разница между цепочкой вызовов и вызовом add_options
несколько раз заключается в том, что в первом случае создается один экземпляр options_description_easy_init
, и каждый раз, когда вы вызываете operator()
на нем, он добавляет параметры владельцу (options_description
). Если вы вызывали add_options
несколько раз, каждый вызов создавал бы новый экземпляр options_description_easy_init
.
Ответ 2
Вопрос о преимуществе субъективен, но в этом случае это краткость.
Сравните это с одним из моих домашних проектов:
("help,h", "Generate this help message")
("output-file,o", po::value<std::string>(), "Output filename. Required.")
("tangent,t", "Generate/load tangent-space basis.")
("collada-output,c", "Write a Collada file, rather than our mesh XML format.")
("arrays,a", "Write arrays instead of indexed verts. Cannot combine with Collada writing.")
("flip-tangent,f", "Change the tangent-space basis matrix handedness. Negates bitangent.")
("map", po::value<std::string>(), "Map filename. Defaults to the ColladaConv directory 'stdmap.txt' file.")
("vao", po::value<std::vector<std::string> >(), "Sequence of mappings, of the form:\n"
"Name # # # #\n"
"\n"
"Each # is an attribute index to use for this VAO.\n"
"Each VAO name must be unique; you cannot use the same VAO in the same place.")
:
visible.add_options()("help,h", "Generate this help message")
visible.add_options()("output-file,o", po::value<std::string>(), "Output filename. Required.")
visible.add_options()("tangent,t", "Generate/load tangent-space basis.");
visible.add_options()("collada-output,c", "Write a Collada file, rather than our mesh XML format.");
visible.add_options()("arrays,a", "Write arrays instead of indexed verts. Cannot combine with Collada writing.");
visible.add_options()("flip-tangent,f", "Change the tangent-space basis matrix handedness. Negates bitangent.");
visible.add_options()("map", po::value<std::string>(), "Map filename. Defaults to the ColladaConv directory 'stdmap.txt' file.");
visible.add_options()("vao", po::value<std::vector<std::string> >(), "Sequence of mappings, of the form:\n"
"Name # # # #\n"
"\n"
"Each # is an attribute index to use for this VAO.\n"
"Each VAO name must be unique; you cannot use the same VAO in the same place.");
Величина длины. И не нужно иметь visible.add_options()
перед всем, что облегчает чтение.