struct do_nothing{ template<class...Args> void operator()(Args&&...)const{}};
template<class...cmd>
struct maybe_run_t;
template<> struct maybe_run_t<>:do_nothing{};
template<class cmd>struct maybe_run_t<cmd>{
cmd&& value;
template<class...Args>
void operator()(Args&&...args)const{
value(std::forward<Args>(args)...);
}
};
template<class...Args>
maybe_run_t<Args...> maybe_run(Args&&...args){
return {std::forward<Args>(args)...};
}
:
int x = 3;
auto f = [x](auto&&...cmd)mutable { maybe_run(cmd...)(x); std::cout << x << std::endl; };
// is there anything I can do here to make f print 4?
f([](auto&x){x=4;});
f();
プリント4\n4\n
。
オプションの引数があります。 1つを渡すと、x
が変更されます。そうしないと、コードは機能します。
また、その存在または戻り値に基づいてフロー制御を行うこともできます。
あなたは代替案について考えるべきです。 'x'を参照として取り込み、それを関数のパラメータにするか、lambdasを使わないで、オーバーロードされた' operator() 'と' x' setterを持つクラスを使います。 – Rames
"*私はそうすることを考えるべきではないという魅力的な理由はありますか?*"意味がないので?あなたがそうする必要があると思ったら、ラムダは何をしようとしていても間違ったツール*です。 –