C++ templates are really useful.
For example, when you design an algorithm, with templates,
you can make it work -
with all possible data containers and data types,
yet you only need to write the function once.
But there is a price to pay:
The program size.
Even if you tell the compiler to optimize a program for size,
you may still be looking at a pretty hefty binary,
which may be a problem
especially if you are developing for an embedded platform.
Luckily C++ also offers a solution to this problem.
Instead of templatizing the whole algorithm,
you might only template the parts -
that depend on your data and your parameters.
To do that, we use virtual functions.
We use a purely abstract baseclass.
The purpose of the baseclass is to define the interface -
that our function will be using.
This interface can then be implemented by derived classes.
The same template will generate a new inherited class -
for each and every datatype that might come acrosss.
As you can see from this chart,
the executable file size does still increase -
every time you add a new type,
but much, much less, than it did -
when the entire algorithm was a template.
Now I am not going to lie to you: This is a tradeoff.
While this trick does make the program smaller,
it also makes it somewhat slower.
But the speed difference seems to be a constant,
and does not depend on the number of types -
that the algorithm is specialized for.
The bottom line is this:
There is never a solution -
that is the best tool for every possible situation.
Part of being an experienced programmer is being well educated -
in a wide variety of techniques and knowing when to use them.
If you are a beginning programmer,
you are probably better off with a small toolbelt -
and learning to use those efficiently.
If you have too many tools as a beginner,
you may get overwhelmed by the number of choices.
But when you gain more experience,
your toolbelt will get larger and larger,
and you'll be making more and more refined programs.
Many people ask me how to keep motivated as a programmer.
How to keep improving?
How to become good?
And my answer is always this:
Always keep being interested to learn how things work.
Never be afraid to experiment.
Aim for just very slightly higher -
than what you are currently able to do,
and you will keep climbing.
There is no cap, other than your imagination.
If you make something interesting, or have a story to share,
post a comment on this video!
I enjoy reading your stories, questions and comments,
and I'm sure others will too.
Thank you for watching,
have a fantastic day, and see you next time.
No comments:
Post a Comment