lundi 28 mai 2018

Variable return template variables in c++

The following code is intended to allow user to access data inside an image which is stored in a vector. The purpose of Pixel structure is to encapsulate variying number of channels in an image by the means of array stored on stack.

(Following code is simplified to provide an overview of the problem)

class Image
{
public:

    const int m_psize;

    Image(int psize) :
        m_psize(psize)
    { }

    template <int psize>
    struct Pixel
    {
        // This array stores pointers to unsigned char
        // which would be stored in Image class

        unsigned char * m_channels[psize];
    };

    // This is my intention \/

    template <int n = this->m_psize>
    Image::Pixel<n> Image::At(int x, int y)
    {
        return Pixel<n>();
    }
}

My question is how would one use templates to allow the following behaviour:

    Image img1(3), img2(3);

    img1.At(2,4) = img2.At(4,3);

But not this:

    Image img1(4), img2(3);

    img1.At(2,4) = img2.At(4,3);

Note: My questions is quite general. I'm not saying this compiles. However, this does:

...
template <int n>
Image::Pixel<n> Image::At(int x, int y)
{
    return Pixel<n>();
}
...

Image img1(3), img2(3);

img1.At<img1.m_psize>(2,4) = img2<img2.m_psize>.At(4,3);

Aucun commentaire:

Enregistrer un commentaire