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

跟風遠走 提交于 2019-12-30 05:45:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!