zklapow
zklapow

Reputation: 133

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 examples. Does anyone know how tot do this?

Upvotes: 2

Views: 3749

Answers (2)

kennytm
kennytm

Reputation: 523254

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.

Upvotes: 5

David
David

Reputation: 2871

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.

Upvotes: 2

Related Questions