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

Time:02-04

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);
}

CodePudding user response:

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.

CodePudding user response:

In C 20 you can constrain it with a concept:

#include <type_traits>

template <typename T>
concept MemberPointer = std::is_member_pointer_v<T>;

void test() {
    auto foo = [](MemberPointer auto memPtr) {};
}

CodePudding user response:

You can use C 20 requires-clause to do this:

#include <type_traits>

auto l = [](auto pmf) requires std::is_member_function_pointer_v<decltype(pmf)>
{
  S s;
  (s.*pmf)();
};

Demo

  •  Tags:  
  • Related