在Swift中使用C 模板

Use C++ Template in Swift

本文关键字:模板 Swift      更新时间:2023-10-16

这是我的CPP模板:

template <typename T>
class CppTemplate1
{
public:
    CppTemplate1(){}
    T Mul(T a, T b){ return a*b; }
};

我在OBJ C中实例化:

@interface templatetest<__covariant T: id>()
@property CppTemplate1<T> m_temp;
@end
@implementation templatetest
- (instancetype)init {
    return self;
}
- (_Nullable id)Mult: (_Nullable id) a sec: (_Nullable id) b{
    return _m_temp.Mul(a, b);
}
@end

现在我想在Swift中使用它:

let m = templatetest<Int>()
let s = m?.mult(3, sec: 5)
print(s)

我在第一个Swift行中有此编译错误:

'Int' is not convertible to 'AnyObject'

我认为您在Objective-C 中实例化,而不是Objective-C。

由于模板在编译时进行了扩展,因此无法直接从不基于C 的任何语言中消耗它们。