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

前端 未结 5 1023
我在风中等你
我在风中等你 2020-12-15 19:51

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

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 20:29

    Like the others, I don't see a fundamental reason why it is not possible.

    (EDIT 2020: Just found this proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1169r0.html)

    In some cases might conflict, according to other rules, with member/static overloading which is not allowed in C++ (again, not sure why).

    struct A{
      void f();
      static int f(); // compile error 
    }
    

    So even if it were allowed to have a static operator(), should this be permitted?

    struct A{
      void operator()();
      static int operator()(); // should be a compiler error??? 
    }
    

    Anyway, there is only one true reason to have a static operator() that it is not purely a syntactic reason and it is that objects should be able to call static functions as if they were member functions.

    struct A{
       static int f():
    }
    ...
    A a; 
    a.f(); // calls A::f() !!!
    

    Specifically, the user of the class A doesn't need to know if a function is implemented as static or as a member. It can later be upgraded to a member function from a generic point of view.

    Leaving that important application to generic programming aside, there is a workaround the leads to a similar syntax that I saw in https://quuxplusone.github.io/blog/2018/03/19/customization-points-for-functions/, and that is to have a static member function called _, a name that doesn't imply any meaning.

    struct A{
        static int _();
    }
    ...
    A::_(); // instead of the more desirable (?) A::() or A::operator()
    a._(); // this invokes the static functon _ 
    

    Instead of the more desirable A::() or A::operator(), (well are they desirable at all? I don't know; something like A() would be really interesting but doens't even follow the syntax of a static function and can be confused with a constructor).

    (As I said, the only feature I still miss, regarding this limitation you point out, is that a() cannot automatically delegate to a static version of the operator(), e.g. A::operator().)

    In summary, your code could look like this:

    struct L{
        static void _() const {} 
        operator auto () const{ 
            return L::_();
        }
    };
    
    L ell; 
    ell(); // calls L::_() really.
    

    Not sure what are willing to achieve still.

提交回复
热议问题