Inheritance requires extra memory for virtual table. Templates can generate more code. When designing embedded application what approach should I select, or how to find proper mix.
Here is the example.
The application has a concept of a MessageReceiver - object that can receive messages from abstract source. I can have multiple implementations for MessageReceiver. MessageReceiver is injected to a particular object that works with messages.
Should I use templates or inheritance. What is more efficient?
Inheritance doesn't necessarily require a virtual table. Polymorphism does.
Dynamic polymorphism and static polymorphism solve different problems. Normally you want to do as much statically as possible, because the compiler is able to verify the types involved. You only use dynamic polymorphism if the type of an object depends on an unknown variable.
Your problem sounds like a use case for dynamic polymorphism. I'm unsure how templates could help here.
ClientA uses references and runtime inheritance, ClientB uses static polymorphism with templates. I have 2kB of SRAM and 32kB of program memory on my controller. I am trying to understand if using runtime inheritance will take significant amount of memory. Is it preferable to use templates for embedded development?
Or both approaches don't impact memory consumption?
Yeah, but ClientA has capabilities that ClientB doesn't. When you declared clientB you were forced to specify at compile time the type of the receiver you want, while with ClientA the type could be determined at run time, even though you didn't do it that way.
1 2 3 4 5 6 7 8 9 10 11
class ConcreteMessageReceiverA : public MessageReceiver {
public:
Message receive() override;
};
class ConcreteMessageReceiverB : public MessageReceiver {
public:
Message receive() override;
};
ClientA clientA(rand() % 2 ? new ConcreteMessageReceiverA : new ConcreteMessageReceiverB);
If you don't need this functionality then you should not be using dynamic polymorphism.
another question. When code uses static polymorphism, is it a compiler who can inline template functions, therefore optimize the code or it is me, developer, who needs to explicitly inline functions where needed?
First of all, note that inline no longer has any effect on inlining behavior. Compilers may inline functions without inline and not inline functions with inline. Some compilers provide specific specifiers to force or disable inlining, but you should never specify inlining behavior unless you have very good reasons to do it.