
On 08/05/2011 16:04, Lorenzo Caminiti wrote:
auto /* or the real type */ l = overload(l1, l2);
Does Boost already have a functor overloader like overload() above?
I do not think so.
template<typename F0, typename F1, typename F2 = void, typename F3 = void> struct overload { };
template<typename F0R, typename F0A0, typename F1R, typename F1A0> struct overload<F0R (F0A0), F1R (F1A0)> { overload(boost::function<F0R (F0A0)> f0, boost::function<F1R (F1A0)> f1): f0_(f0), f1_(f1) {} F0R operator()(F0A0 a0) const { return f0_(a0); } F1R operator()(F1A0 a0) const { return f1_(a0); } private: boost::function<F0R (F0A0)> f0_; boost::function<F1R (F1A0)> f1_; };
// More specializations to overload also with F2, F3, etc.
The type erasure appear unnecessary, and this implementation has big forwarding problems. What about template<typename F0, typename F1> struct overload_t : F0, F1 { overload_t(F0 const& f0, F1 const& f1) : F0(f0), F1(f1) { } using F0::operator(); using F1::operator(); }; template<typename F0, typename F1> overload_t<F0, F1> overload(F0 const& f0, F1 const& f1) { return overload_t<F0, F1>(f0, f1); } Function pointers will have to be dealt with specially, though.