Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Achieve functor overloading through composition

Given some existing functors:

struct incr {
    int operator()(int x) const { return x + 1; }
};

struct rep_str {
    std::string operator()(const std::string& s) const { return s + s; }
};

I'm wondering if it's possible to achieve something like this:

auto f = overload<incr, rep_str>();
f(1);        // returns 2
f("hello");  // returns "hellohello"

Multiple overloads may look like:

auto f = overload<fa, fb, fc, ...>();
// or...
auto g = overload<fa, overload<fb, overload<fc, ...>>>();

I'm thinking maybe use SFINAE with std::result_of_t or something like that, but haven't figured out how.

like image 531
Zizheng Tai Avatar asked Dec 24 '22 03:12

Zizheng Tai


1 Answers

You don't need anything too fancy: just inherit from all the arguments and use using-declarations to bring in operator() from the base classes. However, in the variadic case, you can't have a pack expansion in a using-declaration, so you have to use a recursive approach, like so:

template <class... Ts>
struct overload {}; // only used for empty pack

template <class T>
struct overload<T> : private T {
    using T::operator();
};

template <class T1, class T2, class... Ts>
struct overload<T1, T2, Ts...> : private T1, overload<T2, Ts...> {
    using T1::operator();
    using overload<T2, Ts...>::operator();
};
like image 72
Brian Bi Avatar answered Jan 23 '23 03:01

Brian Bi