(Disclaimer: here be esoteric language wonkery. Abandon all hope.)
If you read or write Generic-code-with-a-capitol-‘G’, you may have written or seen code like this:
using std::swap; swap( a, b );
The first line brings std::swap into consideration, and the second makes an unqualified call to the swap function. I call this the “Std Swap Two-Step”.
Why do we do the Two-Step? It has to do with the decidedly wonky way C++ resolves function calls in templates. I won’t fully elaborate on two-phase name lookup (you’re welcome), but suffice it to say that we do it for the sake of genericity: We make an unqualified call to swap in order to find an overload that might be defined in a and b‘s associated namespaces (itself a rich topic), and we do using std::swap so that, on the off-chance that there is no such overload, we find the default version defined in the std namespace.
We call swap and functions like it customization points — hooks used by generic code that end-users can specialize to customize the behavior for their types.
Are there other standard customization points? You bet. When you use a range-based for loop, the compiler inserts calls to unqualified begin and end to get the bounds of the range. So begin and end are customization points. Depending on how you read the specification of std::reverse, iter_swap may also be a customization point. (I think it is, or that it should be.) And other customization points may be in the offing. Proposal N4155, proposes non-member size for fetching the size of a range, and my own N4128 will propose size as a customization point as well.
Trouble With The Two-Step
Have you seen code that makes qualified calls to swap in a template, like std::swap( a, b ); ? Congratulation, you have probably found a bug. If the type of a and b overloads swap in its own namespace, a qualified call to std::swap won’t find it. It’s an all-too-easy mistake to make.
The problem with the Two-Step is that is forces users to type more to do the right thing. FAIL. Most damning, it requires users to either blindly memorize and regurgitate the Two-Step pattern, or worse: understand two-phase name lookup in templates.
Through With The Two-Step
We need a better solution for the design of customization points in C++. In my own range library, I gave a great deal of thought to the problem, and I think I have an answer. Below is how I would like to see a future version of the Standard Library define std::begin, to pick an example at random. I explain it after the break:
namespace std
{
namespace __detail
{
// define begin for arrays
template<class T, size_t N>
constexpr T* begin(T (&a)[N]) noexcept
{
return a;
}
// Define begin for containers
// (trailing return type needed for SFINAE)
template<class _RangeLike>
constexpr auto begin(_RangeLike && rng) ->
decltype(forward<_RangeLike>(rng).begin())
{
return forward<_RangeLike>(rng).begin();
}
struct __begin_fn
{
template<class R>
constexpr auto operator()(R && rng) const ->
decltype(begin(forward<R>(rng)))
{
return begin(forward<R>(rng));
}
};
}
// To avoid ODR violations:
template<class T>
struct __static_const
{
static constexpr T value{};
};
template<class T>
constexpr T __static_const<T>::value;
// std::begin is a global function object!
namespace
{
constexpr auto const & begin =
__static_const<__detail::__begin_fn>::value;
}
}
Let’s break this down. First, we define a couple of begin free functions in a std::__detail namespace. These overloads handle array types and range-like things with .begin() member functions. (Think of the standard containers.)
Next, we define a __begin_fn class with an overloaded function call operator in the std::__detail namespace that returns the result of making an unqualified call to begin. At this point in the source code, the name begin refers to a function overload set.
Finally, we define a std::begin object of type std::__detail::__begin_fn in a round-about sort of way, the details of which are not too relevant. The important bit is that std::begin is a function object.
Implementers of range-like types can hook this customization point the same way they always have: by defining a begin free function in their type’s associated namespace. See below:
namespace NS {
struct S {};
int * begin( S & s );
}
int main() {
NS::S s;
int *p = std::begin(s); // calls NS::begin(s)
}
Function Objects and Customization Points
Argument-dependent lookup and customization points are a match made in heaven. But argument-dependent lookup is only done for free functions, and my std::begin is a function object. Argument-dependent lookup isn’t done for function objects. What’s going on?
The short answer is that the std::begin function object is doing the Two-Step so that you don’t have to. If std::begin were defined this way, you could just make qualified calls to std::begin and the right thing would happen. You could also do the Two-Step, bringing std::begin into scope with a using declaration, and calling it unqualified, and get the same behavior. Either way, if there is a begin free function defined in the argument’s associated namespace, it will get used.
A subtle but important point is that, if you do the Two-Step, the call is still routed through the std::begin function object. I mean that in the code below:
using std::begin; begin( v );
…if std::begin were an object instead of a function, then what looks like an unqualified function call is not; it’s a call to std::__detail::__begin_fn‘s overloaded function call operator. Think of this as the Generic equivalent of the Gang of Four‘s Template method pattern:
In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure. This use of “template” is unrelated to C++ templates.
— Wikipedia
In this case, the “algorithm” is std::begin, and the certain steps that users can redefine is begin. What’s the point, you ask? We can do extra parameter checking in std::begin. Read on.
Customization Points and Concepts Lite
Customization points are scary in a way. In today’s language, if you define a free function called swap, it better do what the Standard Library expects swap to do. Otherwise, all hell breaks loose in the standard algorithms. Likewise, you can shoot yourself if you define a begin or end free function that doesn’t return iterators. So the Standard Library has laid claim to those names globally. That’s why customization points are such a concern for the standardization committee; the more we add, the more names we reserve globally, and the bigger the potential problem gets for the users.
Enter Concepts Lite. With Concepts Lite, we can constrain our customization points to only work with the types that model certain concepts. For instance, it should be an error to call std::begin on something that doesn’t look like a range, don’tcha think? With Concepts Lite and global function objects, we can have that. We can define std::__detail::__begin_fn like this:
// A _RangeLike is something we can call begin(r)
// and end(r) on:
concept _RangeLike<class T> =
requires(T t) {
typename IteratorType<T>;
{ begin(t) } -> IteratorType<T>;
{ end(t) } -> IteratorType<T>;
requires Iterator<IteratorType<T>>;
};
struct __begin_fn
{
// LOOK! R must be _RangeLike!
template< _RangeLike R >
constexpr auto operator()(R && rng) const ->
decltype(begin(forward<R>(rng)))
{
return begin(forward<R>(rng));
}
};
First we define the _RangeLike concept as something on which we can call begin and end, such that they both return iterators of the same type. (Or, if you agree with N4128, different types that are comparable.) Then we use the _RangeLike concept to constrain __begin_fn::operator() and by extension std::begin. Now std::begin won’t compile for things that aren’t sufficiently range-like, which makes it safer to lay claim to a common identifier like begin.
If std::begin is a function object as opposed to a free function, it’s not easy to route around this concept checking. Code that does the Two-Step won’t accidentally hijack some unrelated begin function in some random namespace. It will always resolve to std::begin, which will politely reject invalid code.
You don’t have to wait for Concepts Lite to reap the benefits, either. See my post on emulating Concepts Lite in C++11.
Summary
What’s all this mean? Simply:
- Users could just call
std::beginand it would do ADL for them. std::begin(rng)wouldn’t compile unless:- it returns an iterator, and
std::end(rng)also compiles and returns an iterator of the same type.
- Code that does
using std::begin; begin(rng);isn’t going to dispatch to some randombeginfunction unless the argument satisfies the constraints ofstd::begin.
More generally, there is a design pattern that we can use to make safe and convenient customization points. If you’re writing a generic library with customization points, I recommend using this pattern.
Addendum: An Ode to Global Function Objects
We get an additional benefit from making std::begin a global function object:
- You can pass
std::beginas an argument to higher-order functions.
That’s a benefit of function objects over free functions in general, and it’s why I generally prefer global function objects over free functions these days (except when I’m defining customization points). Defining global function objects is more work, but it has the nice effect of turning off argument-dependent lookup, which really only makes sense for operator overloads and customization points. First-order functions rule. ADL sucks (except in the few places where it’s awesome).
Update
A quick note about generic lambdas, since I’ve gotten questions. In C++14, we can define polymorphic function objects very concisely using generic lambdas. So can we use lambdas to define global function objects and save some typing, as below:
// Better?
constexpr auto begin = [](auto && rng) {
using __detail::begin;
return begin(forward<decltype(rng)>(rng));
};
The answer, sadly, is no for a host of reasons:
- Lambdas do not have
constexprconstructors. - I don’t know how to solve the ODR problem for lambdas. If
std::beginwere defined this way, then each translation unit would see differentstd::beginobjects at different addresses. In theory, that could cause problems. - I don’t know how to constrain a generic lambda.
- With automatic return type deduction, invalid calls to
begincause a hard error rather than being SFINAE’ed away. That might not be a huge problem forstd::begin, but it most certainly is a huge problem forstd::__detail::begin. Thebeginoverloads found by ADL must use SFINAE (or concept checks); otherwise, you would end up trying to call.begin()on some object that doesn’t have a.begin()member function.
In short, even in C++14, I think we need the ugly hackery I show. Maybe C++17 will bring relief.
Leave a Reply