如果我想支持从 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;
提前致谢!
最佳答案
如果您想混合使用这些语言,或者您发现一种语言更适合特定任务,您始终可以使用 Objective-C++。通常,您可以通过将文件扩展名更改为 .mm
来编译为 ObjC++。
对于 ObjC 接口(interface),您可以考虑像这样的简单包装器接口(interface),它使用您现有的程序:
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)];
}
...
关于objective-c - Objective C 中的 C++ 模板替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12173145/