我阅读了“Modern C++ Design”中的类型列表,并将其理解为某种类型的联合。通过在类型列表中放入不相关的类型,可以一次表示多个类型,而不需要继承。我使用原始类型在一些简单函数中测试了类型列表,但是我无法让它们中的任何一个工作。如何使用类型列表
有人可以告诉我,如果我的类型列表的unterstanding是正确的,并给一个简单的现实世界的例子如何在每一天平均代码中使用类型列表?提前致谢。
顺便说一句,我使用Windows和Visual Studio 2005及其编译器。
编辑:我的例子不见了,我用VS中的沙箱项目来测试这些东西。但它很安静类似于多布斯教程,代码:
void SomeOperation(DocumentItem* p)
{
if (TextArea* pTextArea = dynamic_cast<TextArea*>(p))
{
... operate on a TextArea object ...
}
else if (VectorGraphics* pVectorGraphics =
dynamic_cast<VectorGraphics*>(p))
{
... operate on a VectorGraphics object ...
}
else if (Bitmap* pBitmap = dynamic_cast<Bitmap*>(p))
{
... operate on a Bitmap object ...
}
else
{
throw "Unknown type passed";
}
}
这工作,但我没有看到过继承它能够做同样的优势。动态类型转换不适用于原始类型。是否有可能将其作为一个返回值,如:
typedef Typelist<int, string> mylist
mylist myfunction() {
if(foo == bar)
return 5;
return "five";
}
添加一个不适用于您的问题的代码示例。 – 2009-05-23 16:54:57