0

I'd like to have something like this:

struct Foo {
    template <typename T>
    void operator()(T i) const { /* ... */
    }

    template <typename T>
    auto To() const {    // Doesn't work!
        return this->*static_cast<void (Foo::*)(int) const>(&Foo::operator());
    }
};

Basically, I'd like to obtain a functor from a member function pointer. The above code would have worked if instead of operator() I had used a static function (having gotten rid of all the this->* and Foo:: parts). If I only return the member function pointer auto ptr = static_cast<void (Foo::*)(int) const>(&Foo::operator()), I can use it, e.g., by providing a Foo* pointer foo as foo->*ptr(0);: this motivates this->* in the above code. Is there a nice way to achieve this objective without resorting to lambdas? I'd like to just return a function pointer that "embeds" the information of the specific Foo instance from which it was created.

P.S.: I don't want solutions with lambdas because I'm only curious about solutions without them.

fdev
  • 127
  • 12
  • What about [`std::mem_fn`](https://en.cppreference.com/w/cpp/utility/functional/mem_fn)? – Human-Compiler Jun 11 '21 at 15:37
  • 2
    What you are looking for is this: https://gcc.godbolt.org/z/hnnYzj61j But do note that lambdas are literally nothing but synctactic sugar for that pattern, so there's no reason whatsoever to not use them instead. –  Jun 11 '21 at 15:38
  • 1
    From their previous question, it's clear that OP wants the equivalent of a capturing lambda, so std::mem_fn and the like don't apply. –  Jun 11 '21 at 15:39
  • @Frank I really like your solution, it's what I was looking for, i.e., some sort of wrapper class. I'd be happy to accept it as the answer to my question! – fdev Jun 11 '21 at 15:49
  • 2
    @fdev At the risk of repeating myself. This is literally just doing the exact same work the compiler is required to do when using a lambda while polluting the namespace. Don't do that. Just use a lambda. –  Jun 11 '21 at 16:04
  • I'll definitely use lambdas, but I was just curious about an alternative solution! Thanks again! – fdev Jun 11 '21 at 16:14

0 Answers0