It is well-known that STL classes do not use virtual methods anywhere (and STL does not use inheritance anywhere, too, and that these two facts are inter-related), and that STL is not unique in that.
Let’s assume that other performance freaks exist on earth [well they exist], such performance freaks who ask themselves for every class “do I need virtual methods for this class X ?” and “can this class X do without any virtuals, just like STL classes, for better performance ?”
Absense of any virtual methods (inclusing d’tor) makes polymorphism and subclassing more difficult than with “virtuals” base classes. Apparently “non-virtuals” classes are not well suited to be base classes.
Question: is there technique (for c++) that allows programmer to create in one shot two versions of same class X, a “non-virtuals” version Xnv (for performance), and “virtuals” version Xv, for subclassing ? If this is not needed, please explain why.
Post-note
People answered
“If you need subclassing, use virtuals. If you don’t, don’t use virtuals”.
There is a problem with this suggestion. Couple of problems.
1) needs undergod changes changes over time. subclassing from class X was not needed then, but is needed now, or vice versa.
2) Person who writes the base class is not the same person who writes the derived class. This is clear from the question. People have different thinking stypes, different judgements, different needs. Clear, again.
3) Hence different programmers, answering question like “does inheriting from class X makes any sense?”, will give different answers. It is subjective, there is no cut-in-stone answer.
4) It contradicts what question asks.
Hence we want to satisfy two ends of the spectrum — which happens often in engineering — and this is motivation behind the question.
The motivation was too complex to express concisely in the question. I assumed people can either (1) assume motivation exists as question was precisely formulated, or can (2) figure motivation because they already were in similar tradeoff-and-balance situation of c++ design.
Nobody figured the motivation — to my surprise — possibly even now. This shall be a lesson for me.
I accepted the answer that mentioned CRTP because it is hilarious pattern.
Why do that, when you can have your cake and eat it too?
With CRTP, you have compile-time polymorphism, and the ability for subclasses to override behavior, without any overhead for virtual functions.
Alternatively, you could use a “traits” class to inject behavior.