Cpp templates


#1

i have been wondering if the current api is to big wen it could be more compact
templates seem to be a way to optimise the binary as in unused functions don’t get compiled and have more overloading capabilities (i still don’t fully understand it)

so i was wondering if most of the api could get optimised with this

one of the things that comes to mind is custom display buffers


#2

Ah templates, one of my favourite subjects.

Yes and no.

In most cases any functions that aren’t used, template or otherwise, don’t get compiled - that’s an aspect of functions, not just templates.

Conversely, for templates, if two classes that are exactly the same in every aspect but their name are both used to instantiate a template, despite the two clases being practically the same a block of code will be generated for each, leading to more code use.

(However, chances are that’s code you would have been writing anyway and the templates will save you having to reimplement the same function for a different type.)


There probably are places in the library where templates might be of use, but they are not a cure-all and the reason for adding them should be ease-of-use, not optimisation (unless specific cases of templates providing optimisation can be proven).

For example one potential use that I played with a few days ago:

template < typename T >
void fileWriteObject(const T & value)
{
  fileWriteBytes(reinterpret_cast<const uint8_t *>(&value), static_cast<uint16_t>(sizeof(T)));
}

template < typename T >
uint16_t fileReadObject(T & value)
{
  return fileReadBytes(reinterpret_cast<uint8_t *>(&data), static_cast<uint16_t>(sizeof(T)));
}

template < typename T >
bool fileTryReadObject(T & value)
{
  return (fileReadObject(&value) == sizeof(T));
}

(Note that I haven’t tested this and I’m aware of several potential issues that I’d have to review such as struct padding/packing and endianness. I think it’s a step in the right direction but a way from being optimal.)


In the right hands templates can save a lot of effort, but when it comes to optimisation it depends on the circumstances.
I’ll give you some examples if you want to know more, but I’ll stop there to save this comment from getting too long (which it would do - I’d happily spend a couple of hours discussing templates).


#3

Yep. The gcc compiler is actually very good in paring down unnecessary stuff. I’ve taken some time to read the .map files output by the compiler, and come to the conclusion its not as dumb as I originally thought. In fact, when optimizing code, you more often have to stop the compiler from optimizing out stuff you need.