Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top