次のような呼び出し可能なタイプがあるとします。
struct mutable_callable
{
int my_mutable = 0;
int operator()() { // Not const
return my_mutable++;
}
};
メンバー変数を変更するmutable_callable非定数があることに注意してくださいoperator().....
ここstd::functionで、自分のタイプからout を作成するとします。
std::function<int()> foo = mutable_callable{};
今私はこれを行うことができます:
void invoke(std::function<int()> const& z)
{
z();
}
int main()
{
invoke(foo); // foo changed.....oops
}
今、私の知る限りstd::functionsがoperator()あるconstごとに:
https://en.cppreference.com/w/cpp/utility/functional/function/operator()
だから、私の直感は、あなたがこれを行うことができないはずだということです...
しかし、次に見て:https : //en.cppreference.com/w/cpp/utility/functional/function/function
これは、呼び出し可能な型に定数があるかどうかに制約を課していないようですoperator()......
だから私の質問はこれです:それstd::function<int()> const&は本質的にそれと同じものであると仮定するのは正しいですstd::function<int()>&が、実際には2つの動作に違いはありません......そしてそれが事実である場合、なぜそれがconst正しくないのですか?
std::function実装の内部の小さなスニペットです。i.stack.imgur.com / eNenN.pngここでusing _Ptrt = _Func_base<_Ret, _Types...>。私はケースを休ませる。
std::functionはそれに相当するstruct a{ std::any x; };.....