Search code examples
c++lambdafunction-pointersautopointer-to-member

How to constrain an auto lambda parameter to a pointer to member function?


I have a generic lambda function that needs to accept a pointer-to-member-function as a parameter. I can of course simply use auto on its own and the compiler will deduce the correct type. However, where possible, I prefer to decorate my auto parameters with *, & and const where appropriate, thus better communicating the nature and intent of the deduced type. If I simply make the auto parameter an auto*, I get a compiler error, which I'm not really surprised by as auto* signifies a regular pointer, not a pointer-to-member. Is there some syntax for constraining an auto parameter to accept a pointer-to-member, or should I just use auto and forget about it?

int main()
{
    struct S { void m() {} };

    //auto l = [](auto* pmf) // ERROR
    //auto l = [](const auto& pmf) // Works, but uh, bit misleading I think
    auto l = [](auto pmf)
    {
        S s;
        (s.*pmf)();
    };

    l(&S::m);
}

Solution

  • You can declare it as:

    auto l = [](auto S::*pmf)
    

    It does tie the pointer to a S type, but it makes sense because it is that way you will use it.