c – 为什么无状态函子的operator()不能是静态的?
作者:互联网
为什么不允许无状态函子的operator()不是静态的?无状态lambda对象可转换为指向与其operator()具有相同签名的自由函数的指针.
Stephan T. Lavavej on p. 6指出转换为函数指针只是一个运算符FunctionPointer()(引用).但我无法获得与非成员函数相对应的operator()指针.对于functor struct F {void operator()(){}},似乎不可能使用P = void(*)();将& F :: operator()转换为类型的实例.
码:
struct L
{
static
void operator () () const {}
operator auto () const
{
return &L::operator ();
}
};
错误是
overloaded ‘operator()’ cannot be a static member function
但是operator()没有重载.
解决方法:
按照标准13.5 / 6,
An operator function shall either be a non-static member function or be a non-member function and have
at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an
enumeration.
另外,在13.5.4中说明了这一点
operator()
shall be a non-static member function with an arbitrary number of parameters. It can have
default arguments. It implements the function call syntax
postfix-expression
(
expression-list
opt
)
where the
postfix-expression
evaluates to a class object and the possibly empty
expression-list
matches
the parameter list of an
operator()
member function of the class. Thus, a call
x(arg1,…)
is interpreted
as
x.operator()(arg1, …)
for a class object
x
of type
T
标签:c,lambda,c14,functor,function-pointers 来源: https://codeday.me/bug/20191001/1837731.html