Search code examples
c++lambdafunction-pointersc++14functor

Why can't operator () of stateless functor be static?


Why is operator () of stateless functor not allowed to be static? Stateless lambda objects are convertible to pointers to free functions having the same signature as their operator ().

Stephan T. Lavavej on p. 6 points out that conversion to a function pointer is just an operator FunctionPointer() (cite). But I can't obtain a corresponding pointer to operator () as to non-member function. For functor struct F { void operator () () {} } it seems to be impossible to convert &F::operator () to instance of type using P = void (*)();.

Code:

struct L
{
    static
    void operator () () const {} 
    operator auto () const
    { 
        return &L::operator ();
    }
};

The error is

overloaded 'operator()' cannot be a static member function

but operator () is not overloaded.


Solution

  • Per standard [over.oper] p6:

    An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

    Additionally, in [over.call] p1 it is stated that:

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

    postfix-expression ( expression-listopt )

    where the postfix-expression evaluates to a class object and the possibly empty expression-list matches the parameter list of an operator() member function of the class. Thus, a call x(arg1,...) is interpreted as x.operator()(arg1, ...) for a class object x of type T.


    Note: These restrictions have been lifted in C++23, so operator() can be static.