CRTP + compile-time introspection + static ctors = WIN

Jacob Carlborg doob at me.com
Mon Jan 18 16:49:03 UTC 2021


On 2021-01-15 19:31, H. S. Teoh wrote:

> Yesterday, I hit upon a nice solution: use CRTP (the Curiously-Recursive
> Template Pattern) to inject these methods into each derived class:
> 
> 	class Saveable(Derived, Base) : Base {
> 		static if (is(Base == Object)) {
> 			// Top-level virtual function
> 			void save() { ... }
> 		} else {
> 			// Derived class override
> 			override void save() { ... }
> 		}
> 	}
> 
> 	class Base : Saveable!(Base, Object) { ...  }
> 
> 	class Derived1 : Saveable!(Derived1, Base) { ... }
> 
> 	class Derived2 : Saveable!(Derived1, Base) { ... }
> 

That's an interesting idea. Although it's a bit intrusive since it 
requires changing what you're serializing.

In my serialization library Orange [1] I solved this by registering 
subclasses that are going to be serialized through a base class 
reference [2]. If they're not serialized through a base class reference, 
no registration is required.

[1] https://github.com/jacob-carlborg/orange
[2] 
https://github.com/jacob-carlborg/orange/blob/1c4b1ab989fc36e6fae91131ba6951acf074f383/tests/BaseClass.d#L73

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list