读书人

应用联合结构的类,有什么好办法对数据

发布时间: 2013-07-01 12:33:04 作者: rapoo

使用联合结构的类,有什么好办法对数据进行存取?
先上代码:


enum ImageType
{
_NIL_,
_RGBA_,
_RGB_,
_XYZ_,
_YXY_,
_LUV_,
_LAB_,
_HSB_,
_HSL_,
_HSI_,
_GRAY_,
};

class _BoiExport Image
{
public:
template <ImageType id> struct Type
{
enum { number = id };
};

//默认构造函数,空图像
Image();

//构造指定类型和尺寸的的图像
Image(ImageType _type, long width, long height);

//析构函数
virtual ~Image();

//返回当前格式的图像矩阵的共享矩阵
#define GET() Get(Image::Type<type)

//清空图像
void Release();

//判断图像是否为空
bool IsEmpty() const;

//图像格式
ImageType type;

//图像矩阵
union
{
Matrix<RGBA_>* rgba;
Matrix<RGB_ >* rgb;
Matrix<XYZ_ >* xyz;
Matrix<YXY_ >* yxy;
Matrix<LUV_ >* luv;
Matrix<LAB_ >* lab;
Matrix<HSB_ >* hsb;
Matrix<HSL_ >* hsl;
Matrix<HSI_ >* hsi;
Matrix<GRAY_>* gray;
};

//获取图像格式
static ImageType Id(const std::string& type_name);

//返回RGBA格式的矩阵
Matrix<RGBA_>*
Get(Type<_RGBA_> cid) const;

//返回RGB格式的矩阵
Matrix<RGB_>*
Get(Type <_RGB_> cid) const;

//返回XYZ格式的矩阵
Matrix<XYZ_>*
Get(Type <_XYZ_> cid) const;

//返回YXY格式的矩阵
Matrix<YXY_>*
Get(Type <_YXY_> cid) const;

//返回LAB格式的矩阵
Matrix<LAB_>*
Get(Type <_LAB_> cid) const;

//返回LUV格式的矩阵
Matrix<LUV_>*
Get(Type <_LUV_> cid) const;

//返回HSB格式的矩阵
Matrix<HSB_>*
Get(Type <_HSB_> cid) const;

//返回HSL格式的矩阵
Matrix<HSL_>*
Get(Type <_HSL_> cid) const;

//返回HSI格式的矩阵
Matrix<HSI_>*
Get(Type <_HSI_> cid) const;

//返回GRAY格式的矩阵
Matrix<GRAY_>*
Get(Type<_GRAY_> cid) const;
};


我想设计一种结构来统一的保存从文件中读取的不同格式的图像数据,对他们进行管理,并能够方便的进行存取和修改。现在使用联合,返回值不同,不知道怎么能统一接口呢?现在的办法是重载再加上一个很不优雅的宏实现的数据提取,感觉挺不靠谱的。

有没有高手能提供某种模式或数据结构的资料或代码参考一下啊! 联合 数据 存取 模式
[解决办法]
可以借鉴ImageMagick库(http://www.imagemagick.org/script/index.php)的做法。
[解决办法]
不要用联合:

class image_data_base
{
public:
virtual ~image_data_base(){}
virtual void get_row_data( vector<byte_t> & row_data, size_t width, size_t height ) const = 0;


virtual void set_row_data( vector<byte_t> const & row_data, size_t width, size_t height ) = 0;
virtual byte_t get_alhpa( size_t x, size_t y) const = 0;
virtual void set_alpha( size_t x, size_t y, byte_t value) = 0;
virtual rgb_t get_rgb( size_t x, size_t y) const = 0;
virtual void set_rgb( size_t x, size_t y, rgb_t const & value ) = 0;
virtual cmyk_t get_cmyk( size_t x, size_t y) const = 0;
virtual void set_cmyk( size_t x, size_t y, cmyk_t const & value ) = 0;
virtual hsl_t get_hsl( size_t x, size_t y) const = 0;
...
};
class rgb_image_data
{
public:
...
rgb_t get_rgb( size_t x, size_t y )
{
return data[x,y];
}

unsigned int get_alpha( size_t x, size_t y )
{
return 255;
}
//其它获取和设值函数中进行计算或抛出异常。
};




分别为每种数据格式写一个派生类。这是假定数据长度都为字节的情况,如果要支持不同数据长度,把基类和生类都写成模板,再写一个从image_data_base<double>派生的adaptor模板,将其它类型数据转换为double类型。

读书人网 >C++

热点推荐