在操作符重载中使用可变参数模板合法吗? [英] Is it legal to use variadic templates in operator overloading?

查看:61
本文介绍了在操作符重载中使用可变参数模板合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够按照以下方式写点东西:

I would like to be able to write something along these lines:

struct bar {};

template <typename ... Args>
bar operator+(bar, Args ...)
{}

我刚刚用clang/gcc进行了检查,就像我一样,二元表达式( a + b )和一元表达式( + a )都选择了重载运算符会期望的.但是,运算符比普通函数受到更多的限制,例如,您不能用三个参数重载 operator +().

I just checked with clang/gcc and the overloaded operator is picked up both by binary expressions (a+b) and unary expressions (+a), as I would expect. However operators are more restricted than normal functions, in the sense that - for instance - you cannot overload operator+() with three arguments.

用法是否合法且可移植?

Is the usage above legal and portable?

编辑为了提供一些背景信息,我显然不希望能够定义可变参量运算符或任何种类的运算符.我对此感兴趣的原因是一个丑陋的骇客:我想使一些运算符可变,以便我可以用其他非可变实现替代"它们.由于在函数模板重载规则中,可变参数模板被认为比非可变参数模板更不专业,因此我可以用非可变运算符覆盖可变参数运算符.是的,这很可怕:)

EDIT To give a bit of context, I am clearly not expecting to be able to define variadic operators or anything of the sort. The reason I am interested in this is for a ugly hack: I would like to make some operators variadic so that I can "override" them with other non-variadic implementations. Since variadic templates are considered to be less specialised than non-variadic templates in the function template overloading rules, I could override a variadic operator with a non-variadic one. Yes it's pretty horrid :)

推荐答案

首先,定义很好,因为存在带有非空包 1 的有效专业化名称.

First off, the definition fine, because there exist valid specializations with non-empty packs1.

现在,特定的表达式 a + b + a 是i.a.分别转换为 operator +(a,b) operator +(a)形式的非成员调用( [over.match.oper]/6 只是委托给像往常一样重载解析:

Now, specific expressions a+b or +a are i.a. transformed into non-member calls of the form operator+(a, b) and operator+(a), respectively ([over.match.oper]/2). Name lookup then finds the operator function template, whose specialization becomes part of the candidates. Finally, [over.match.oper]/6 just delegates to overload resolution as usual:

用于重载解决方案的候选函数集为成员候选人,非成员候选人和内置成员考生.参数列表包含的所有操作数操作员.候选函数集中的最佳函数是根据13.3.2和13.3.3选择.

您的代码也将按预期工作,因为重载解析和部分排序将像其他所有代码一样尊重操作员功能模板.

Your code will also work as intended, since overload resolution and partial ordering will respect the operator function template like all others.

1 为一元运算符声明以上内容,但后缀- ++ 除外,它们格式错误,无需诊断.cf. [temp.res]/(8.2).

1 declaring the above for unary operators, except perhaps postfix -- and ++, is ill-formed, no diagnostic required. Cf. [temp.res]/(8.2).

这篇关于在操作符重载中使用可变参数模板合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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