Sometimes in my code, I find myself wanting to define several instances of the same class, with the difference in the definition being small relative to its overall length, and sharing some common designator. And - I struggle to refactor the code so that it's both compact and easy to use.
Example: I start with:
auto blue_foo = std::make_unique<float[]>(n);
auto blue_bar = std::make_unique<float[]>(m);
auto blue_baz = std::make_unique<float[]>(k);
This is kind of icky: Repetition of commands and name prefixes... :-(
I can put this these variables in a struct named blue, so that I could write
do_stuff_with(blue.foo, blue.baz, 123);
rather than
do_stuff_with(blue_foo, blue_baz, 123);
but - then I would need even more repetition:
struct {
std::unique_ptr<float[]> foo, bar, baz;
} blue = {
std::make_unique<float[]>(n),
std::make_unique<float[]>(m),
std::make_unique<float[]>(k),
};
So wasteful! I would have at least liked to write something like:
struct { auto foo, bar, baz; } foo = {
std::make_unique<float[]>(n),
std::make_unique<float[]>(m),
std::make_unique<float[]>(k),
};
but that's not possible.
Also, I don't want to repeat the make_unique call. I could write a lambda, I suppose:
auto make_data = [](std::size_t size) { return std::make_unique<float[]>(size); }
struct { auto foo, bar, baz; } blue = { make_data(n), make_data(m), make_data(k) };
but the lambda is a lot of writing; and it doesn't save all that much. And even that has some repetition.
What is an idiomatic approach for maiing my initial piece of code compact and readable?
Note: In the example, the code snippet is not repeated many times; just once. If I repeatedly used a combination of foo, bar and baz I would write a class for holding them.
You can make a helper function that returns
std::tupleofunique_ptrand then use structure bindings. The general idea is as follows: