const std :: function包装了一个非const operator()/可变lambda [英] A const std::function wraps a non-const operator() / mutable lambda
问题描述
请考虑以下示例:
#include <iostream>
#include <functional>
struct A
{
int i;
void operator()()
{
std::cout << ++i;
}
};
void test(std::function<void()> const& fun)
{
fun();
}
int main() {
const std::function<void()> f{A{}};
test(f);
test(f);
}
这里是常量
std :: function
可以调用非< const
operator()
。
Here, a const
std::function
is able to call a non-const
operator()
.
输出:
12
如果我提供可变
lambda,例如, test([x = 0]()可变{++ x;});
The same happens if I supply a mutable
lambda e.g. test([x = 0]() mutable { ++x; });
那怎么可能?
const std :: function
可以包装可变函子是正常的吗?
Is it normal that a const std::function
may wrap a mutable functor?
推荐答案
const std :: function
是否正常?可能包装了可变的函子?
Is it normal that a
const std::function
may wrap a mutable functor?
不幸的是,是的。 std :: function :: operator()
无条件地限定为 const
,并且不在乎是否包装可调用
被突变。一些论文试图解决这个问题,但是AFAIK尚未决定具体的事情:
Unfortunately, yes. std::function::operator()
is unconditionally qualified as const
and doesn't care whether or not the wrapped Callable
is mutated. Some papers attempted to tackle this issue, but AFAIK nothing concrete was yet decided:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0045r1.pdf
这篇关于const std :: function包装了一个非const operator()/可变lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!