Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "using std::begin;" a good practice?

As I have read, begin(some_vector) is more standard than some_vector.begin() because of array support... and as I know also, the use of using keyword is not really desirable behavior. However, I also see lot of code that contains just these two usings:

using std::begin;
using std::end;

Is that considered good or bad practice? Especially when many begin and end are needed?

like image 759
Humam Helfawi Avatar asked Nov 30 '22 17:11

Humam Helfawi


2 Answers

It can be helpful for ADL help. Something like:

template<typename T, typename F>
void apply(T& v, const F& f)
{
   using std::begin;
   using std::end;
   std::for_each(begin(v), end(v), f);
}

So, than we just can call apply with types, that have begin/end functions and classic C arrays.

In other case it's actually okay to use using directive in source file, in little scope and so on, but it's bad to use in header.

like image 38
ForEveR Avatar answered Dec 04 '22 04:12

ForEveR


As I have read, begin(some_vector) is more standard than some_vector.begin() because of array support

It's not "more standard", both are 100% standard. It is more generic, because it works for arrays, but it's not actually very common to have an object and not know whether it's an array or a container type. If you have something that you know is an array then use std::begin(a) but if you have something that you know is not an array then there is no advantage to using the form that also works with arrays. If you're in a generic context where you might have either, then std::begin works for both cases.

the use of using keyword is not really desirable behavior.

That's debatable. There are very good reasons to avoid using-directives in most contexts (i.e. using namespace foo) but the same arguments don't apply to using-declarations that introduce a single name (i.e. using foo::bar). For example the recommended way to use std::swap is via using std::swap so it's certainly not true that the using keyword is undesirable in general.

Is that considered good or bad practice? Especially when many begin and end are needed?

I would say that in general it's a bad idea. As the other answers explain, it allows begin and end to be found by ADL, but that's not necessarily a good thing. Enabling ADL for begin and end can cause problems, that's why we changed range-based for at the last minute to not use using std::begin; using std::end; to avoid ambiguities, see N3257 for the details.

like image 59
Jonathan Wakely Avatar answered Dec 04 '22 03:12

Jonathan Wakely