Re: Design question about using templates
On Feb 22, 1:27am, Anja <anja.e...@googlemail.com> wrote:
> Hi everyone,
>
> I am using a third party library that uses templates quite heavily for
> generalization. It is an image processing library and for example a
> typical "Image" class has the following definition:
>
> Image<PixelType, Dimensions>
>
> The PixelType here represents the data type of the underlying
> data...could be anything from chars to complex numbers and the
> Dimensions are the dimensions of the image...which could be 2D to 4D
> (3D and time).
>
> Now, my problem is that I need to instantiate and store these
> objects in my class. With non-templated objects it is trivial as
> everything is known at compile time.
>
> However, with this object, I do not know the PixelType and Dimensions
> till run-time! So, I cannot, for example, have a member variable in a
> class of the Image type. However, that is exactly what I need to do. I
> need to create the image object and then later access this image
> object and use its functions.
>
> What design options do I have? I am pretty sure people have had this
> problem before. What solutions can I choose from?
<...>
It depends on the Docs for your image type.
My guess is that you are meant to supply your own types, but they will
need to conform to some set of rules e.g interface or concept.
Anyway wrapping different entities into one
can be achieved by creating a wrapper, e.g lets call it pixel . pixel
contains a pointer to an abstract base class, from where you can
derive your actual own pixel types.
IOW something like:
template <
typename PixelType,
typename Dimensions
>
struct Image
{
Image( Dimensions const & d)
{
}
};
// base class for real pixel types
struct abc_pixel_type{
virtual ~abc_pixel_type(){}
};
// various real pixel types
struct col_pixel : abc_pixel_type{
/****/
};
struct gray_pixel : abc_pixel_type{
/****/
};
struct png_pixel : abc_pixel_type{
/****/
};
// common wrapper for various pixels
struct pixel{
// somehow construct form real pixels...
pixel(gray_pixel const & in)
: m_pixel(new gray_pixel(in)){}
pixel(png_pixel const & in)
: m_pixel(new png_pixel(in)){}
pixel(col_pixel const & in)
: m_pixel(new col_pixel(in)){}
~pixel(){ delete m_pixel;}
private:
abc_pixel_type * m_pixel;
};
// wrap dimensions
struct dimension{
dimension(int x, int y): m_xvalue(x),m_yvalue(y){}
private:
int m_xvalue;
int m_yvalue;
};
int main()
{
Image<pixel,dimension> my_image(dimension(1024,768));
}
However this will only be useful if you make sure you conform to the
requirements of the image type of course ....
regrads
Andy Little
|