0

I'm trying to use the PImpl idiom to use the <vector> libray in my Objective-C project.

I have managed to implement it, but it only for the Int type as you can see in my .h and .mm file.

file.h

#import <Foundation/Foundation.h>
struct Vector_impl;
@interface MM_Matrix : NSObject
{
    struct Vector_impl *MMVec;
}
    @property unsigned rows, columns;

- (MM_Matrix *) initwith:(int) n and: (int) m;
- (long) size: (int) n;

file.mm

#import "MM_Matrix.h"
#include <vector>

struct Vector_impl
{
    std::vector<std::vector<int>> matrix;
};
@implementation MM_Matrix : NSObject

- (MM_Matrix *) initwith:(int) n and:(int)m
{
    [self setRows:n];
    [self setColumns:m];
    MMVec = new Vector_impl;
    MMVec->matrix.resize(n);
    for (int i=0; i<n; i++) {
        MMVec->matrix[i].resize(m, 0);
    }
    return self;
}
- (long) size: (int) n
{
    return MMVec->matrix[n].size();
}
@end

I would like to implement a generic type (template maybe?) as you would do in the <vector> library, but I have no idea how to achieve that.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Artanis
  • 15
  • 3

1 Answers1

0

Assuming that you want to template std::vector<std::vector<int>>: there are two possibilities:

  • Use a weak type, e.g. void* and take care of conversion inside the class.
  • Implement an interface for every type you want to support.

For the second option it is enough to instantiate the template class for every type, so that the compiler knows which types are used.

Also have a look at this related question: pimpl for a templated class.

Community
  • 1
  • 1
Sebastian
  • 8,046
  • 2
  • 34
  • 58
  • I like the idea of the void pointer but I don't have idea how to harness the code of pimpl to obtain that. Any hint please? – Artanis Dec 30 '13 at 02:56
  • Basically the interface functions for e.g. adding/removing elements take `void*`. Then you'll have to take care about type conversion, where you could i) define explicit conversion functions or ii) pass the length of a single element in bytes. But, if you are using i) you could also use instantiate the template class for every type to be supported. – Sebastian Dec 30 '13 at 07:23