objective-c - Objective C 中的 C++ 模板替换

标签 objective-c templates

如果我想支持从 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/

相关文章:

ios - "_nano_vet_and_size_of_live"仅在 iOS 10 中出现崩溃

ios - GKMatchRequest playerGroup 属性不起作用

iphone - PrepareForSegue 方法将文本从两个不同的 TextView 传递到下一个 View 中的 TextView

c++ - 当 Type 为 unique_ptr 时,为 vector 添加 operator[]

templates - 如何用逗号连接领事模板的服务元数据

iphone - UITableViewCell 的动态高度和里面的内容

iphone - 从其 subview 中删除WEPPopover

c++ - 将基于自定义模板的迭代器类的对象转换为 const_iterator

python - 如何在 C++ 中为 Cython 中的两种类型使用模板化函数?

c++ - 是否可以在派生类中选择性地定义类型