Problems with inheritance in the STL
在http://www.stepanovpapers.com/notes.pdf中,Alexander Stepanov提到:
It is interesting to note that the only examples of inheritance that
remained in STL inherit from empty classes. Originally, there were
many uses of inheritance inside the containers and even iterators, but
they had to be removed because of the problems they caused.
号
排除在STL中使用继承的技术问题是什么?
我想我会直接发表一些来自Alexander Stepanov的评论(http://www.stlport.org/resources/stepanovusa.html)。
Question:
STL is full of creative uses of templates, such as symbolic
types exported from classes, or the pattern matching of a set of
overloaded algorithms onto iterator tags. Surely enough, no standard
C++ Programming book speaks about those idioms. How did you come to
these C++ code idioms?Answer:
I knew exactly what I was trying to accomplish. So I tweaked
the language until I was able to get by. But it took me many years to
discover all the techniques. And I had many false starts. For example,
I spent years trying to find some use for inheritance and virtuals,
before I understood why that mechanism was fundamentally flawed and
should not be used. I am very happy that nobody could see all the
intermediate steps - most of them were very silly. It takes me years
to come up with anything half decent. It also helped that Bjarne was
willing to put certain features in the language just to enable some of
my idioms. He once refered to it as"just in time language design."
号
接下来,我将允许自己引导您找到这个伟大的答案:
https://stackoverflow.com/a/1039904/210971
OOP is not the holy grail. It's a cute idea, and it was quite an
improvement over procedural languages back in the 70's when it was
invented. But it's honestly not all it's cracked up to be. In many
cases it is clumsy and verbose and it doesn't really promote reusable
code or modularity.That is why the C++ community is today far more interested in generic
programming, and why everyone are finally starting to realize that
functional programming is quite clever as well. OOP on its own just
isn't a pretty sight.
号
现在我想说:
OOP规则规定了程序员思考事物(对象、实体、摩擦物等)之间交互的方式(继承、多态性等)。
在添加泛型支持之前,在这个简单的Java示例中,可以清楚地看到这一点(但这些并不像C++中那样冗长)。
1 2 3 | List v = new ArrayList(); v.add("test"); Integer i = (Integer)v.get(0); // Run time error |
虽然代码没有错误编译,但它在执行第三行代码时抛出运行时异常(Java.Lang.CasasStExtExtExchange)。这类问题可以通过使用泛型来避免,并且是使用泛型的主要动机。
1 2 3 | List<String> v = new ArrayList<>(); v.add("test"); Integer i = v.get(0); // (type error) compilation-time error |
号
Alexander Stepanov认识到通用方法可以解决这个问题,有助于在数据结构和算法之间提供逻辑分离(抽象)。这就是为什么对迭代器、函数和许多其他非常适合通用世界的习语如此强调的原因。