[英]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.我有一个通用的 lambda function 需要接受指向成员函数的指针作为参数。 I can of course simply use
auto
on its own and the compiler will deduce the correct type.我当然可以简单地使用
auto
,编译器会推断出正确的类型。 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.但是,在可能的情况下,我更喜欢在适当的地方用
*
、 &
和const
装饰我的自动参数,从而更好地传达推导类型的性质和意图。 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.如果我只是将
auto
参数设为 auto auto*
,则会出现编译器错误,对此我并不感到惊讶,因为auto*
表示常规指针,而不是指向成员的指针。 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?是否有一些语法可以约束
auto
参数以接受指向成员的指针,或者我应该只使用auto
并忘记它?
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);
}
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.它确实将指针绑定到
S
类型,但这是有道理的,因为您将使用它。
In C++20 you can constrain it with a concept:在 C++20 中,你可以用一个概念来约束它:
#include <type_traits>
template <typename T>
concept MemberPointer = std::is_member_pointer_v<T>;
void test() {
auto foo = [](MemberPointer auto memPtr) {};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.