开发者

Alternative for templates in C++

I wrote code that looked like the following:

template<typename CocoaWidget>
class Widget : boost::noncopyable
{
private:
  Cocoa开发者_StackOverflow社区Widget* 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?


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).


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜