Karl von Moor
Karl von Moor

Reputation: 8614

Alternative for templates in C++

I wrote code that looked like the following:

template<typename CocoaWidget>
class Widget : boost::noncopyable
{
private:
  CocoaWidget* mCocoaWidget;

public:
  Widget()
  {
    mCocoaWidget = [[CocoaWidget alloc] init];
  }

  // ...
};

class Button : Widget<NSButton>
{
  // ...
};

But that doesn't work, because Mac Dev Center says:

Objective-C classes, protocols, and categories cannot be declared inside a C++ template

So what shall I do now best?

Upvotes: 3

Views: 354

Answers (2)

kennytm
kennytm

Reputation: 523224

What's wrong? Your code is working. My similar test case compiled and run without leaks.

#import <Foundation/Foundation.h>

template <typename T>
class U {
protected:
        T* a;
public:
        U() { a = [[T alloc] init]; }
        ~U() { [a release]; }
};

class V : U<NSMutableString> {
public:
        V(int i) : U<NSMutableString>() { [a appendFormat:@"%d = 0x%x\n", i, i]; }
        void print() const { NSLog(@"%@", a); }
};

int main() {
        U<NSAutoreleasePool> p;
        V s(16);
        s.print();
        return 0;
}

Upvotes: 0

Martin B
Martin B

Reputation: 24140

Are you sure you can't do this (have you tried)?

The quote from Mac Dev Center says you can't declare an Objective-C class inside a template. What you're doing, however, is merely declaring a pointer to an Objective-C object inside a template -- quite a different thing, and I don't see a reason why it shouldn't be allowed (though I have never tried).

Upvotes: 5

Related Questions