Consider this question, which is about the following code not compiling:
std::vector<int> a, b; std::cout << (std::ref(a) < std::ref(b));
It doesn't compile because the vector comparison operators for vector
are non-member function templates, and implicit conversions aren't allowed to be considered. However, if the operators were instead written as non-member non-template, friend
functions:
template <class T, class Allocator = std::allocator<T>> class vector { // ... friend bool operator<(const vector& lhs, const vector& rhs) { // impl details } };
Then this version of operator<
would have been found by ADL and been chosen as the best viable overload, and the original example would have compiled. Given that, is there a reason to prefer the non-member function template that we currently have, or should this be considered a defect in the standard?
Many-to-one: All instantiations of a template function may be friends to a regular non-template class. One-to-one: A template function instantiated with one set of template arguments may be a friend to one template class instantiated with the same set of template arguments.
We can not change operator templates.
Given that, is there a reason to prefer the non-member function template that we currently have, or should this be considered a defect in the standard?
The reason is if ADL could find out proper function or not. When such a search requires to extract the substituted template parameters from the type of given object and then substitute them many times into a templated parameter of the function template, ADL can't do this because of there are no reasons in the general case to prefer one way of template parameters binding to other. The non-member function template defined after but still in the namespace scope of that template (due to friend
) excludes such an indeterminacy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With