Alternative for templates in C ++

I wrote code that looks like this:

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

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

  // ...
};

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

But this does not work, because Mac Dev Center says:

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

So what am I best to do now?

+3
source share
2 answers

Are you sure you cannot do this (have you tried)?

A quote from the Mac Dev Center says that you cannot declare an Objective-C class inside a template. However, you simply declare a pointer to an Objective-C object inside the template is a completely different matter, and I see no reason why this should not be allowed (although I have never tried).

+5
source

? . .

#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

Source: https://habr.com/ru/post/1732824/


All Articles