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

2019-09-09 03:33发布

问题:

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