For an embedded design, I made a featherweight class. A C++ construct that used no more data or code size than a traditional C design.
class command { public: inline command(uint32_t steps, bool reverse) : cmd_(steps << 1 | (reverse ? 0 : 1)) { assert(steps <= (UINT32_MAX >> 1)); } inline operator uint32_t() const { return cmd_; } friend uint32_t steps(const command &cmd); friend bool reverse(const command &cmd); private: uint32_t cmd_; };
It's an interesting little structure. In memory, any object just takes the exact same size as an uint32_t.
The code size (if this class is used somewhere) is tiny too. Only the code of the constructor will be inline inserted into your code base. Any other code of that class is optimised away. Using this class is exactly the same as using an unsigned int, and using a shift then set its last bit.
This is a class that can hold a number of steps, and a direction bit, in a 32 bit variable. Bit 0 (LSB) is the direction, all the other bits are the number of seps a stepper motor would take
This info is passed to a stepper motor API. My library - after creating the class object - does not need to know what part of the uint32_t is the number of steps, and what's the direction.
But you, as a user, may be interested in that info. Maybe to check the requested steps and make decisions on that. Maybe to know what direction the motor is turning.
Friend Functions
I could extend the class definition, and provide the logic to extract dir and steps from that single uint32_t. But most firmware wouldn't need it. Nonetheless, I added that possibility to the class definition, as a set of friend clauses. friend functions have access to the object's protected and private sections.
With the current state of compiler optimisation, I could have used member functions in the command class. If they aren't used in your project, the optimiser will happily cull them. So don't read this post as an optimisation exercise. I used the friend structure here s a lazy mechanism: I'll implement it if I need it |
My commands class is listed at the start of this post. You can see that it accepts two functions as friend:
I can now declare these functions outside the class, and use them in my firmware. This is an implementation of the functions. Again very cheap. It will result in assembly that just returns the data member.
inline uint32_t steps(const command &cmd) { return cmd.cmd_ >> 1; } inline bool reverse(const command &cmd) { return !(cmd.cmd_ & 1); }
And here I use them in firmware:
for (auto &c: cmds) { printf("steps %d, reverse %d\n", steps(c), reverse(c)); }
You may not need friend functions in your code base. But it's one of the tools that you can use to make reusable APIs.
Are there downsides? Yes: they weaken class encapsulation. Under a known contract though.
Thank you for reading.