问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/30265207/should-operators-be-declared-as-non-member-non-template-friends