So here is something I just discovered I can do in C++ that I didn't know about.
template class wrapper{public: wrapper(const T &t){ } int length() const { return -1; }};template<> class wrapper{public: wrapper(const StringEntity &e) : e(e) { } int length() const { return e.text.length(); } StringEntity e;};template<> class wrapper{public: wrapper(const ListEntity &e) : e(e) { } int length() const { return e.elements.size(); } ListEntity e;};template void process(const wrapper &w){ std::cout << "process: " << w.length() << "\n";}int main(){ StringEntity s("hello"); ListEntity l; wrapper se(s); wrapper le(l); process(se); process(le);}
Compile time polymorphism, but of completely unrelated types and no use of virtual methods.
My scripting language has both String and List types which are completely unrelated, but have a lot of overlap in terms of the operations the VM needs to do on them.
StringEntity and ListEntity do happen to both inherit a base class, but that is irrelevant for the subject here - could add a specialisation for any other class here.
This approach should mean I can define a common interface without affecting any of the other Entity classes, and use template functions to do the processing.
Call today's entry a snippet since I'm actually at work :)
Novel use of template specialization :)