2012-05-07 65 views
16

我寫一個使用Boost的程序選項庫的程序,我注意到下面的語法,因爲我看到它已經困擾我:升壓程序選項添加選項語法

desc.add_options() 
     ("help","produce help message") 
     (/* other flag, value, description pairs here */) 
; 

我看到,在標題中,運營商()被覆蓋,但我不確定這是如何讓它在語法上是正確的。

其次,與多次調用add_options()相比,這個語法是否有優勢(除了展示你可以像這樣操作語法的事實)?

+5

該提升作者喜歡炫耀... –

+0

「鬧鬼」是一個很好的描述...我正式得到它,但「感覺」奇怪... – thomastiger

回答

16

add_options成員函數返回options_description_easy_init類型的對象。後者有operator()重載以返回對自身的引用。這允許您按照您在代碼段中所示的方式鏈接呼叫。

鏈接呼叫和呼叫add_options幾次的區別是,在每次創建的options_description_easy_init單個實例在前一種情況下,你調用它operator(),其添加的選項所有者(options_description)。如果您要多次撥打add_options,每次呼叫都會創建一個options_description_easy_init的新實例。

+1

+1如何,但它仍然要求問題:爲什麼? – paulrehkugler

+0

@paulrehkugler尼科爾的[回答](http://stackoverflow.com/a/10487655/241631)解釋了爲什麼 – Praetorian

12

優勢問題是主觀的,但在這種情況下它是簡潔的。

比較這離我家項目之一:

("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's handedness. Negates bitangent.") 
("map", po::value<std::string>(), "Map filename. Defaults to the ColladaConv directory's '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's handedness. Negates bitangent."); 
visible.add_options()("map", po::value<std::string>(), "Map filename. Defaults to the ColladaConv directory's '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(),這使得它更易於閱讀。

+0

我懷疑這是唯一的優勢。在我看來,這只是一個更好的工作來製作更漂亮的代碼。 – paulrehkugler

+0

這兩個例子都很可怕。你可以定義'options_description_easy_init o = visible.add_options()',只需調用'o(「help」,「生成此幫助信息」);'? – Vortico

+0

@Vortico:我沒有看到任何特別令人不愉快的第一例。事實上,即使它有效,我也沒有看到你的建議對第一個建議有什麼好處。我不知道會不會;你必須檢查Boost的文檔才能看到。但通常,從這樣的結構中保留中間體不是一個好主意。 –