Using c++ template an argument to an objective-c method
How can I use a c++ template as an a parameter to an objective-c method? essentially I want to do something like this:
template<typename T>
- (void)method:(T)arg
but that doesn't work. according to this document this is possible however it does not provide any examp开发者_运维技巧les. Does anyone know how tot do this?
No you can't do that.
Objective-C classes, protocols, and categories cannot be declared inside a C++ template, nor can a C++ template be declared inside the scope of an Objective-C interface, protocol, or category.
Even if it is possible to declare that template, it is useless as Objective-C methods cannot be overloaded by type.
When the documentation says "C++ template parameters can also be used as receivers or parameters (though not as selectors) in Objective-C message expressions", that means that you can call an Objective-C method from within a templated C++ class or function, not that you can actually make a templated Objective-C method.
For example:
template<typename T>
void f(id obj, T t) {
[obj doSomethingWithObject:t];
}
...should work (although I haven't tested it). Of course, the type used when calling f
would have to be something that could validly be passed as a parameter to doSomethingWithObject:
, otherwise the calling code wouldn't compile.
精彩评论