0

To start off, i'm quite the noob at c++, and i'm lost. I've googled for hours but I think my problem is either niche or too easy. Here goes:

I'm writing a c++ mex file to be used from matlab. However, I would like to allow both single as double precision inputs. So I want to use templates to achieve this.

I've this class:

template< typename T > class img {
    T *_data;
public:
    img (T *_data) : _data(_data) {}
    T &operator[]( int i ) { return _data[ i ]; }
}

Then in the main.cpp:

void mexFunction( int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
    if (mxIsDouble(prhs[0])) {
        double *f = (double *)mxGetPr( prhs[ 0 ] );
        img<double> myimg(f);

    } else if (mxIsSingle(prhs[0])) {
        float *f = (float *)mxGetPr( prhs[ 0 ] );
        img<float> myimg(f);
    }

mexPrintf( "value of myimg[%d] = %f\n", 10, myimg[10] );
}

Now the compiler complains about "error: use of undeclared identifier myimg".

I think this is because the object myimg is only existing inside the if scope, right?

If I define the img<double> myimg(f); before the if statement it works, but obviously only for doubles.

Help

P.S. I've found this related stack question: Can a MATLAB Mex function accept both single and doubles?

jww
  • 97,681
  • 90
  • 411
  • 885
Jann5s
  • 33
  • 5
  • 1
    "I think this is because the object `myimg` is only existing inside the `if` scope, right?" - Right. – max66 Jun 03 '18 at 13:23
  • You will have to write an additional template method that does everything that need to be done. Your `if` statement will then instantiate the template, and invoke its method, in both `if` and `else` cases, thus executing the code for the appropriate type. Alternatively, with much work, make the template inherit from a non-template base class, and then implement some primitive [type erasure](https://stackoverflow.com/questions/34815513/what-is-type-erasure-in-c). This opens up the possibility of using dynamically allocated objects. – Sam Varshavchik Jun 03 '18 at 13:31
  • Thanks @SamVarshavchick, that helped. I guess I wanted to avoid the additional template method, but i've implemented it now and works perfectly. P.S. did this question really deserve a downvote? – Jann5s Jun 03 '18 at 15:04
  • I don't think it did deserve a downvote, imo it's a decent question. – MivVG Jun 03 '18 at 17:39

0 Answers0