Question

I am currently writing a function template that deals with a generic container. I want to use std::begin() and std::end(), because of the reasons mentioned in this question. My question is, whether should I use:

std::begin( myContainer )

Or:

using namespace std; // Better use: "using std::begin"
begin( myContainer )

Or, in other words, is it okay to overload begin() within the std namespace? Should I allow users of my function to overload the begin() function in the global namespace somewhere else as well? How does the STL deal with it?

Was it helpful?

Solution

There's no need for a using directive, so let's assume the second snippet contains a using declaration instead.

using std::begin;

If you're creating your own container to go with this function template, provide Container::begin() and Container::end() member functions, and then it doesn't make a difference whether you use the first or the second. std::begin() and std::end() will call the respective member functions when available (§24.7 [iterator.range]).

On the other hand, if you're creating a function template that should work with any container, those present in the standard library, or a custom container; I'd recommend the second approach.

using std::begin;
begin( myContainer );

Note that that will enable ADL to find user defined overloads for free functions begin() and end() within the same namespace as the container definition. The overloads should not be added to namespace std or the global namespace (unless the container definition is also in the global namespace). In the absence of these free function overloads, std::begin will be called (because of the using declaration) and this in turn will call Container::begin().

OTHER TIPS

It's not okay to overload something in std namespace, only specializations are allowed. If you want to enable ADL you can use

using std::begin;
begin(myContainer)

For a custom container, std::begin actually can call begin in your container. So if you have MyContainerClass::begin that will be enough. Same with std::end and the constant-iterator versions std::cbegin and std::cend.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top