2012-10-15 78 views
0

我有一個不是模板類的類,我需要添加一個函數到這個類是一個模板函數。問題是我在需要一個字符串作爲參數的類中調用一個函數,所以我需要製作一個這個模板的專用版本,這樣我纔可以調用這個函數,只要參數是const char*或者在函數只調用函數,如果該參數是const char*但似乎不工作。任何幫助,將不勝感激!如何在非模板類中使用模板專業化? C++

template<class myType> __declspec(nothrow) 
std::string GetStrVal(int row, int col, myType default) { 

    try { 
     CheckColumnType(col, String); 
    } 
    catch(DatatableException e){ 
     return default; 
    } 
    return this->m_rows[row][col]; 
} 

template<class myType> 
std::string GetStrVal(int row, const char* col, myType default) { 

    unsigned int columnIndex = this->GetColumnIndex(col); 
    return GetStrVal(row,columnIndex, default); 
} 

GetColumnIndex()只需要const char*

+1

簽名是不同的,所以你不需要模板專業化。 – andre

+0

編譯器是否真的接受關鍵字'default'作爲標識符(請不要告訴我這是你的實際錯誤,否則你的代碼看起來是合理的,至少在有效性方面)?或者,編譯器無法決定將'unsigned int columnIndex'轉換爲'int'還是'const char *'('int'應該有優先權,但我不確定)。另外請記住,目前'GetStrVal(row,NULL,default)'會調用'int'版本(或者它可能無法做出決定?),這可能是不可預料的。 –

回答

2

你不需要專門化任何東西;你可以只提供一個或兩個過載:

template<class myType> __declspec(nothrow) 
    std::string GetStrVal(int row, int col, myType default); // template 

    __declspec(nothrow) 
    std::string GetStrVal(int row, int col, std::string default); // overload 

    __declspec(nothrow) 
    std::string GetStrVal(int row, int col, const char *default); // overload 
+0

他想專注於'col',而不是模板參數。但仍然是超載是正確的方法。 –