是类型字段纯邪恶? [英] Are type fields pure evil?

查看:130
本文介绍了是类型字段纯邪恶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如第12.2.5节的 c ++编程语言第三版中所述,请键入字段倾向于创建比使用虚拟函数和多态性的等效代码更不通用,容易出错,更不直观,更不易维护的代码。

As discusses in The c++ Programming Language 3rd Edition in section 12.2.5, type fields tend to create code that is less versatile, error-prone, less intuitive, and less maintainable than the equivalent code that uses virtual functions and polymorphism.

,这里是如何使用类型字段:

As a short example, here is how a type field would be used:

void print(const Shape &s)
{
  switch(s.type)
  {
  case Shape::TRIANGE:
    cout << "Triangle" << endl;
  case Shape::SQUARE:
    cout << "Square" << endl;
  default:
    cout << "None" << endl;
  }
}

很明显,这是一个噩梦,因为添加一个新类型对于这种形状和十几个类似的功能将是容易出错和征税。

Clearly, this is a nightmare as adding a new type of shape to this and a dozen similar functions would be error-prone and taxing.

尽管有这些缺点和TC + PL描述,有什么例子,一个实现(使用类型字段)是比利用虚拟函数的语言特性更好的解决方案? 或者这种做法是否被黑名单列为邪恶?

Despite these shortcomings and those described in TC++PL, are there any examples where such an implementation (using a type field) is a better solution than utilizing the language features of virtual functions? Or should this practice be black listed as pure evil?

现实的例子比设计的例子更受欢迎,设计的例子。

Realistic examples would be preferred over contrived ones, but I'd still be interested in contrived examples. Also, have you ever seen this in production code (even though virtual functions would have been easier)?

推荐答案

当你知道的时候, 你有一个非常具体,小,不断的类型集合,它可以更容易硬编码他们这样。当然,常量不是和变量不,所以在某些时候你可能不得不重写整个东西。

When you "know" you have a very specific, small, constant set of types, it can be easier to hardcode them like this. Of course, constants aren't and variables don't, so at some point you might have to rewrite the whole thing anyway.

这或多或少,在几个 Alexandrescu的文章中用于歧视工会的技术。

This is, more or less, the technique used for discriminated unions in several of Alexandrescu's articles.

例如,如果我正在实施 JSON 库,我会知道每个Value只能是一个Object,Array,String,Integer,Boolean或Null - 规范不允许任何其他。

For example, if I was implementing a JSON library, I'd know each Value can only be an Object, Array, String, Integer, Boolean, or Null—the spec doesn't allow any others.

这篇关于是类型字段纯邪恶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆