Difference between a+b and operator+(a,b)

家住魔仙堡 提交于 2019-12-11 19:48:11

问题


Consider the following program:

#include<functional>

typedef std::function< int( int ) > F;

F operator+( F, F )
{
    return F();
}

int f( int x ) { return x; }

int main()
{
    operator+(f,f); // ok
    f+f; // error: invalid operands to binary expression
}

Why does the last line f+f; not compile? Why is it not identical to operator+(f,f);? A reference to the standard would be appreciated.


回答1:


The type of f is a built-in type. Operations on objects of built-in types never consider user-define operators. Calling operator+(f, f) explicitly force two conversions which will not happen unless they are forced. The relevant clause is 13.3.1.2 [over.match.oper] paragraph 1:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5. ...



来源:https://stackoverflow.com/questions/19307578/difference-between-ab-and-operatora-b

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