Last active
December 16, 2015 01:49
-
-
Save hotwatermorning/b592d5ca616194940a42 to your computer and use it in GitHub Desktop.
Apply function to variant variable using generic lambda.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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