Friday 22 December 2017

c++ - Why use non-member begin and end functions in C++11?

itemprop="text">


Every standard container
has a begin and end method for
returning iterators for that container. However, C++11 has apparently introduced free
functions called rel="nofollow noreferrer">std::begin and href="http://en.cppreference.com/w/cpp/iterator/end" rel="nofollow
noreferrer">std::end which call the
begin and end member functions. So,
instead of writing



auto i =
v.begin();
auto e =
v.end();


you'd
write



auto i =
std::begin(v);

auto e =
std::end(v);


In his
talk, rel="nofollow noreferrer">Writing Modern C++, Herb Sutter says that you
should always use the free functions now when you want the begin or end iterator for a
container. However, he does not go into detail as to why you would
want to. Looking at the code, it saves you all of one character. So, as far as the
standard containers go, the free functions seem to be completely useless. Herb Sutter
indicated that there were benefits for non-standard containers, but again, he didn't go
into detail.



So, the question is what exactly do
the free function versions of std::begin and
std::end do beyond calling their corresponding member function
versions, and why would you want to use them?


class="post-text" itemprop="text">
class="normal">Answer



How do you
call .begin() and .end() on a C-array
?



Free-functions allow for more generic
programming because they can be added afterwards, on a data-structure you cannot
alter.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...