Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Nice C++11 idiom

26 views
Skip to first unread message

Richard

unread,
Jan 16, 2018, 3:41:30 PM1/16/18
to
[Please do not mail me a copy of your followup]

Suppose you have some code that is repeated for a bunch of disparate
values. Prior to C++11 you'd typically squish out the difference by
extracting the common code into a named function and then call the
function repeatedly with the disparate values:

void foo(const char *word)
{
std::cout << word << '\n';
}

void bar()
{
foo("bar");
foo("meta");
foo("word");
}

or perhaps you put the disparate values in a C-style array with
aggregate initialization and then looped over the array:

const char *words[] = {"bar", "meta", "word"};
for (int i = 0; i < sizeof(words)/sizeof(words[0]); ++i)
{
std::cout << words[i] << '\n';
}

This required introducing a name for the repeated code/data (not
necessarily a bad idea as it is an opportunity to use an intention
revealing name when the code is complex). However, when the code is
just a few lines, the extra boilerplate of a named function/data might
feel too burdensome. You might also not want to expose those named
entities for fear that someone else will couple to them as they are
just an implementation detail of what you're trying to do in the
small.

With range for loops and std::initializer_list, you can do the
following:

#include <initializer_list>

void bar()
{
for (auto word : {"bar", "meta", "word"})
{
std::cout << word << '\n';
}
}

(The std::cout is admittedly a gratuitous example here, but it
illustrates the idiom.) Now we can just write the repeated chunk of
code without having to extract it into a named function when it is a
small repeated body.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Terminals Wiki <http://terminals-wiki.org>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
0 new messages