Skip to content

Instantly share code, notes, and snippets.

@hotwatermorning
Last active December 16, 2015 01:49
Show Gist options
  • Save hotwatermorning/b592d5ca616194940a42 to your computer and use it in GitHub Desktop.
Save hotwatermorning/b592d5ca616194940a42 to your computer and use it in GitHub Desktop.
Apply function to variant variable using generic lambda.
template<class F, class Ret = void>
struct Apply : boost::static_visitor<Ret>
{
Apply(F f) : f_(std::move(f)) {}
template<class T>
Ret operator()(T &t) { return f_(t); }
template<class T>
Ret operator()(T &t) const { return f_(t); }
F f_;
};
template<class F>
Apply<F, void> make_apply(F f)
{
return Apply<F, void>(std::move(f));
}
template<class Ret, class F>
Apply<F, Ret> make_apply(F f)
{
return Apply<F, Ret>(std::move(f));
}
template<class F, class Variant>
void apply_function(F f, Variant &variant)
{
return boost::apply_visitor(make_apply(std::move(f)), variant);
}
template<class Ret, class F, class Variant>
Ret apply_function(F f, Variant &variant)
{
return boost::apply_visitor(make_apply<Ret>(std::move(f)), variant);
}
void A::foo()
{
apply_function([this](auto &data) { DoProcess(data); }, variant_data_);
}
template<class Data>
void A::DoProcess(Data &data)
{
//do something.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment