2012-08-29 52 views
2

如果我想支持從在C數據庫查詢幾種類型的檢索++我可以創建基於模板的方法定義,就像C++ - 更換模板的目標C

template<typename T> 
T getDBValue(int col){ 
    throw "not implemented"; 
} 

template<> 
int getDBValue<int>(int col){ 
    return 43; 
} 

template<> 
char* getDBValue<char*>(int col){ 
    return "foo"; 
} 

我知道有沒有在Objective-C的模板真正對手,所以有什麼你會用它來支持一些返回值,而不是提前實現這個像

- (type1) getType1FromCol: (int) col; 
- (type2) getType2FromCol: (int) col; 
- (type3) getType3FromCol: (int) col; 

謝謝!

回答

2

查詢它您可以隨時使用的Objective-C++,如果你想混語言,或者如果你發現一個更適合特定的任務。通常,通過將文件擴展名更改爲.mm,您可以編譯爲ObjC++。

對於ObjC接口,你可以考慮一個簡單的封裝接口這樣的,它使用您現有的程序:

template<typename T> 
T getDBValue(int col); // << not defined 

template<> 
int getDBValue<int>(int col){ 
    return 43; 
} 

template<> 
const char* getDBValue<const char*>(int col){ 
    return "foo"; 
} 

你可以接近這樣的:

@implementation MONDBEntry 
{ 
    int col; 
} 
... 

- (int)intValue 
{ 
    return getDBValue<int>(self.col); 
} 

- (NSString *)stringValue 
{ 
    return [NSString stringWithUTF8String:getDBValue<const char*>(self.col)]; 
} 
... 
2

其實只有兩個選擇,這取決於什麼是對用戶而言conventient:

  • 做到如你所說,不同的方法
  • 使用給予不同的名稱,返回任何類型的只是其中的一個方法適用於該項目(基本上將所有單一類型的方法合併爲一個,返回一個泛型類型,如NSObject *甚至id)。顯然只適用於「真實的」對象返回類型,基本要求調用要麼知道正確的結果類型,或從結果