[問題] Parsing 問題想用C++ template 一般化
最近遇到一些問題 雖然可解 但是非常的繁瑣, 首先說明一下最近處理的問題:
從檔案讀出一行一行的字串, 每一行由一個key word + delimeter + value string
所組成, 那程式的任務就是按照已經定義好的key word spec,讀進variable
後再進行後續的處理.
像這樣:
file_name = source.txt
width = 1000
height = 2000
那程式裡就有:
string
int
int
三種type的variable.
我的做法 就是先把 key word 還有value string 兩個token parsing出來, 這個不難
重點是, 我必須針對每個關鍵字寫一個: if (!strcmp(XXXX,XXX))
再用: sscanf(..format_string...) 用不同的format string 讀進不同type的variable.
不知道這有沒有什麼辦法可以用template來做, 根據傳進去container type的不同
就能自動產適當的code, 自己試了一下, 發現在字串還有數值部分沒有辦法一般化.
//===================== pseudo code =============================//
template <typename T>
GetValue(const char* p_pSource, const char* p_pKeyWord,T& p_roContainer )
{
if p_pSource matches p_pKeyWord
p_roContainer <- transformation
}
//==============================================================//
在transformation 這步不能用template來做 主要是因為 sscanf 對於 string type
和int/float/double...等等type的處理方式不同, 不同處為
1. format string不同
2. int/float/double等等 value type的variable要取其位址,如下
char buf[256];
int intValue;
sscanf(source, "%d",&intValue);
sscanf(source,"%s",buf);
(p.s.嘗試考慮過string class...也是不行....)
請大家在這邊給我一些建議 這裡是否有辦法一般化進而能用template自動生成code
這樣我就不用每次都要寫同樣的code了......
在此先謝謝大家了....XD
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.43.206.9
→
12/05 22:49, , 1F
12/05 22:49, 1F
→
12/05 23:22, , 2F
12/05 23:22, 2F
→
12/09 21:43, , 3F
12/09 21:43, 3F