应该将运营商声明为非成员非模板朋友 [英] Should operators be declared as non-member non-template friends

查看:113
本文介绍了应该将运营商声明为非成员非模板朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此问题,这是关于以下代码无法编译的:

Consider this question, which is about the following code not compiling:

std::vector<int> a, b;
std::cout << (std::ref(a) < std::ref(b));

它不会编译,因为向量向量的比较运算符是非成员函数模板,不允许隐式转换考虑。但是,如果操作符改为写为 friend 非成员非模板函数:

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 friend non-member non-template functions:

template <class T, class Allocator = std::allocator<T>>
class vector {
    // ...

    friend bool operator<(const vector& lhs, const vector& rhs) {
        // impl details
    }
};

然后,此版本的运算符< 被ADL发现,被选为最好的可行的超载,原来的例子将编译。鉴于,是否有理由 更喜欢我们目前拥有的非会员功能模板,或者这应该被视为标准中的缺陷?

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?

推荐答案


因此,有理由更喜欢非成员函数

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?

原因是如果ADL可以找出正确的功能或不。当这种搜索需要从给定对象的类型中提取替换的模板参数,然后将它们多次替换为函数模板的模板化参数时,ADL不能这样做,因为在一般情况下没有理由偏好一种模板参数绑定到其他方式。在模板的命名空间范围之后定义的非成员函数模板(由于 friend )排除了这种不确定性。

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.

这篇关于应该将运营商声明为非成员非模板朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆