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

2019-09-09 03:27发布

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条回答
来,给爷笑一个
2楼-- · 2019-09-09 03:42

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. ...

查看更多
登录 后发表回答