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',而不是模板参数。但仍然是超载是正确的方法。 –