简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM