I was just thinking, it’s a shame that the people responsible for the Arduino library chose to use Print
as their solution for text printing.
Being a class with a limited pool of print
and println
functions means it’s hard to introduce functionality for printing kinds of objects (i.e. new types).
Granted there’s the Printable
class, but that won’t work for types like enum class
,
and even on class types, inheriting Printable
forces the implicit sizeof(void*)
overhead (for the pointer to the virtual table) onto the class.
Instead they could have used something more along the lines of <iostream>
's overriding of the <<
operator.
That decision often gets a lot of flak because <<
isn’t the most obvious operator for printing text,
but the decision to allow printing via free functions means that it’s more flexible and easy to extend.
For example it would be possible to print an enum class
simply by providing an overload of the <<
operator.
If anyone actually read this far and is wondering what the hell this has to do with the FX library, I was thinking of ways to print strings read from the FX chip.
As it stands the only possibility I can think of is:
class FXString : public Printable
{
private:
uint24_t address;
public:
FXString() = default;
constexpr FXString(uint24_t address) :
address(address)
{
}
size_t printTo(Print & print) const override
{
// Set FX address.
// Read bytes from FX,
// calling print.write(value),
// until '\0' is encountered.
}
// Other stuff ???
};
Which should end up having a size of 5.
If they had gone for the <<
route then it could have just been:
class FXString
{
private:
uint24_t address;
public:
FXString() = default;
constexpr FXString(uint24_t address) :
address(address)
{
}
constexpr uint24_t getAddress() const
{
return this->address;
}
};
// Returns a `Print &` to allow 'method chaining'
inline Print & operator <<(Print & print, const FXString & string)
{
// Set FX address.
// Read bytes from FX,
// calling print.write(value),
// until '\0' is encountered.
return print;
}
And then FXString
would only have been 3 bytes and there would have been no virtual table involved.