【问题标题】:Use C++ Template in Swift在 Swift 中使用 C++ 模板
【发布时间】:2018-02-24 12:42:38
【问题描述】:

这是我的 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'

【问题讨论】:

  • 泛型参数需要使用NSNumber 而不是Int,因为在Objective-C 中只有类可以用作泛型参数。

标签: c++ objective-c swift templates generics


【解决方案1】:

我认为你是用 Objective-C++ 实例化的,而不是 Objective-C。

由于模板是在编译时扩展的,因此无法直接从任何不基于 C++ 的语言中使用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多