Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should operators be declared as non-member non-template friends

Tags:

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?

like image 920
Barry Avatar asked May 15 '15 17:05

Barry


People also ask

Can we declare a template function as the friend of the class?

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.

Can we change operator templates?

We can not change operator templates.


1 Answers

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.

like image 87
Aleksey F. Avatar answered Oct 07 '22 20:10

Aleksey F.