r/cpp • u/pavel_v • Aug 30 '26
On forcing all derived classes to implement a specific non-virtual method, part 2
https://devblogs.microsoft.com/oldnewthing/20260828-00/?p=112654
67
Upvotes
r/cpp • u/pavel_v • Aug 30 '26
32
u/Electronic_Tap_8052 Aug 30 '26
Huh. I usually accomplish this with a template type that has a function declaration but no implementation. That way there's no 'base class' at all to worry about, and it's all resolved at compile time.
I call it poor man's inheritance.
16
u/Alduish Aug 30 '26
But why ?
Virtual classes have a reason to exist, if you cast the derived object back to the base class (a function that can opperate on any derived objects of this virtual class) then if the function isn't virtual you're gonna call the deleted function and the whole trick will have been useless.
5
u/Gungan_Boss_Nass premature cleverization Aug 30 '26
Possible errors is an interesting sub-category here. I can write requires or static_assert and provide an escape hatch for the caller to bypass it if it's not an error. That covers the 95% probability cases, but feels excessive for the 70% probability cases.
[[deprecated("This is probably wrong")]] with some SFINAE works better for those. You can build and test and only turn off the warning when you're really sure.
2
u/NilacTheGrim Sep 01 '26
Meh. Kinda neat, but not sure how i feel about this.
If you really want to enforce some method be implemented in a certain set of related classes, then presumably you are polymorphic somewhere in some way in your code -- whether this be through traditional polymorphism via vtables, or polymorphism via templates.
If you're using vtables you don't need this technique since in that case you just do the usual
virtual void Convert() = 0.If you're using templates to achieve the polymorphism then you also don't need this because you can use concepts and/or requires clauses to enforce this.
But I guess the usage here is more succinct although it sort of makes the code weirder to maintain -- you have code that CONSUMES these classes that cares about the .Convert() method existing -- but they don't enforce that.
Instead you put the onus on the base class to enforce that "for reasons" that aren't immediately clear when reading the base class.
I would rather just use a concept or a requires clause at the CONSUMING end of this class hierarchy closer to the code that cares whether
.Convert()exits or not... it's easier to maintain and reason about if you ask me.But this is neat.. I'll give Mr. Chen that.
-1
u/Ateist Aug 30 '26 edited Aug 30 '26
WTF is this coding style?!
Examples are extremely hard to read due to multi-layered namespace issues like this.
This is well past the point where it serves its purpose and into the "extremely harmful" territory.
How does code like this pass any code review?