首页 \ 问答 \ “运行时模板”(“run time templates”)

“运行时模板”(“run time templates”)

我很确定答案是“你不能使用模板,你必须使用虚函数(动态多态)”,但似乎我必须复制很多代码,如果我去那条路线。 这是设置:

我目前有两个类,ColorImageSegmentation和GrayscaleImageSegmentation。 它们基本上是相同的,但有三个不同 - 它们在不同的类型(ColorImage和GrayscaleImage)上运行 - 一个参数,直方图的维度(3对1)是不同的 - PixelDifference函数根据图像类型而不同

如果我创建一个类

template <TImageType>
class ImageSegmentation
{
};

我会很好。 但是,我希望将此对象作为另一个类的成员:

class MyMainClass
{
 ImageSegmentation MyImageSegmentation;
};

但是用户需要确定MyImageSegmentation的类型(如果用户打开灰度图像,我想实例化MyImageSegmentation<GrayScaleType> 。同样对于彩色图像, MyImageSegmentation<ColorType> 。)

使用派生类,我可以存储指针,然后执行:

class MyMainClass
{
 ImageSegmentation* MyImageSegmentation;
};

... user does something...
MyImageSegmentation = new ColorImageSegmentation;

但是我怎么用模板做这样的事呢? 问题是我有很多:

typedef TImageType::HistogramType HistogramType;
typedef TImageType::PixelType PixelType;

发生了一些事情,所以我不知道如何将它们转换为动态多态模型而不重复一大堆代码。

对不起,漫无目的......有人对我有什么建议吗?

谢谢,

大卫


I'm pretty sure the answer is "you can't use templates, you have to use virtual functions (dynamic polymorphism)", but it seems like I'd have to duplicate a lot of code if I went that route. Here is the setup:

I currently have two classes, ColorImageSegmentation and GrayscaleImageSegmentation. They do essentially the same thing, but there are three differences - they operate on different types (ColorImage and GrayscaleImage) - a parameter, the dimensionality of the histogram (3 vs 1) is different - The PixelDifference function is different based on the image type

If I create a class

template <TImageType>
class ImageSegmentation
{
};

I would be in good shape. However, I want to have this object as a member of another class:

class MyMainClass
{
 ImageSegmentation MyImageSegmentation;
};

But the user needs to determine the type of MyImageSegmentation (if the user opens a grayscale image, I want to instantiate MyImageSegmentation<GrayScaleType>. Likewise for a color image, MyImageSegmentation<ColorType>.)

With derived classes, I could store a pointer and then do:

class MyMainClass
{
 ImageSegmentation* MyImageSegmentation;
};

... user does something...
MyImageSegmentation = new ColorImageSegmentation;

but how would I do something like this with templates? The problem is I have a lot of:

typedef TImageType::HistogramType HistogramType;
typedef TImageType::PixelType PixelType;

sort of things going on, so I don't know how I would convert them to the dynamic polymorphic model without duplicating a whole bunch of code.

Sorry for the rambling... does anyone have any suggestions for me?

Thanks,

David


原文:https://stackoverflow.com/questions/4233300
更新时间:2024-04-22 14:04

最满意答案

这是一个很好的列表和讨论:

http://css-tricks.com/different-ways-to-format-css/


Here is a good list and discussion:

http://css-tricks.com/different-ways-to-format-css/

相关问答

更多