Why did C ++ designers decide not to allow a statement that is not a member of () ()?

I just play with std::function<>and operators so that C ++ expressions look like functional languages ​​( F#) and find out that there is a difference between operator()and operator<<. My code is:

Function 1 (Operator Overload):

function<int(int)> operator>>(function<int(int)> f1, function<int(int)> f2)
{
  function<int(int)> f3 = [=](int x){return f1(f2(x));};
  return f3;
}

Function 2 (operator overload):

function<int(int, int)> operator>>(function<int(int, int)> f1, function<int(int)> f2)
{
  function<int(int, int)> f3 = [=](int x,int y){return f2(f1(x, y));};
  return f3;
}

Function 3 (Operator Overload):

function<int(int)> operator()(function<int(int, int)> f1, int x)
{
  function<int(int)> f2 = [=](int y){return f1(x, y);};
  return f2;
}

while function 1 and function 2 (or operator overload), function 3 throws an error:

error: ‘std::function<int(int)> operator()(std::function<int(int, int)>, int)’ must be a nonstatic member function
     function<int(int)> operator()(function<int(int, int)> f1, int x)
                                                                    ^

Why operator()should be a non-stationary member? I think it is different from What is the difference between the dot (.) And → operator in C ++? In this question, the answer is explained in terms of pointers. But here I am using simple operator()and operator>>that have nothing to do with pointers.

+4
3

operator>>() , , . :

lhs >> rhs

:

lhs.operator>>(rhs) // non-static member

:

operator>>(lhs, rhs) // standalone function

operator(), , . -, . :

lhs(arguments)

:

lhs(arguments) // only if lhs is an actual function

:

lhs.operator()(arguments) // must be a non-static member

++ :

lhs(arguments)

:

operator()(lhs, arguments)
+2

, . operator() , (std::function ), .

13.5.4 [over.call]

1operator() - . [...]

, =, [] ->, , >>, , ( ) .

+4

operator>>() , operator(). operator() - class struct.

:

13.5.4 [over.call]

1 operator()must be a non-static member function with an arbitrary number of parameters. It may have default arguments. It implements function call syntax

postfix-expression (expression-list opt)

where the postfix expression evaluates the class object and a possible empty list-list corresponds to the list of parameters of the operator()class member function . Thus, the call is x(arg1,...)interpreted as x.operator()(arg1, ...)for an object of the xtype class T, if it T::operator()(T1, T2, T3)exists, and if the operator is selected as the best function of compliance with the overload resolution mechanism (13.3.3).

+1
source

Source: https://habr.com/ru/post/1589535/


All Articles