简体   繁体   中英

Lambda/function of arbitrary arity and with captures as a function argument

In my C++ programme, I often need to build a vector of values of a function on all the possible values of its arguments over some small finite field. For example, something like this:

int q = 7;
vector<int> GFq;
for (int x = 0; x < q; x++) GFq.push_back(x);

auto P = [q](int x, int y) -> int { return (x*x+y) % q; };
auto Q = [q](int x, int y) -> int { return (x+2*y) % q; };
auto f = [q,P,Q](int x1, int y1, int x2, int y2) 
        -> int {return (P(x1,y1) + Q(x2,y2)) % q; }

vector<int> table;
for (int x1: GFq) for (int y1: GFq) for (int x2: GFq) for (int y2: GFq)
    table.push_back(f(x1,y1,x2,y2));

This pattern is so often repeated in my code that I naturally want to make it a function. So I need something like this:

template<typename F>  // not sure if I need to use templates
vector<int> tabulate(int q, F f) {
    // run through values 0..q-1 for all arguments of f
    // and store the values of f to the resulting vector
}

Some questions/issues:

  • I want to be able to pass an arbitrary function to tabulate() including those of different arity (ie f(x) , f(x,y) , etc.)
  • I want to construct the function I pass "on the fly", including usage of other functions (the same way as f is constructed from P and Q in the first code snippet
  • if I manage to pass such a function, how can I run a loop over all possible arguments of f (ie 0..q-1 for each of its arguments) inside tabulate() ?

I want to be able to pass an arbitrary function to tabulate() including those of different arity (ie f(x), f(x,y), etc.)

Make tabulate a template that accepts objects of arbitrary types as functions.

I want to construct the function I pass "on the fly", including usage of other functions (the same way as f is constructed from P and Q in the first code snippet

You can use a lambda directly as a function parameter.

if I manage to pass such a function, how can I run a loop over all possible arguments of f (ie 0..q-1 for each of its arguments) inside tabulate()?

In pseudocode:

params = {0, ..., 0};

while (1)
{
    // Call function with `params` here.

    int i = 0;
    for (i = 0; i < params.size(); i++)
    {
        params[i]++;
        if (params[i] == q)
            params[i] = 0;
        else
            break;
    }
    if (i == params.size())
        break;
}

In practice you need to store parameters in a std::array (or std::tuple , as the code below does), and use std::apply to call your function with these parameters.


A complete implementation:

#include <cstddef>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>

template <typename T, typename ...P, std::size_t ...I>
bool increment_tuple_impl(T q, std::tuple<P...> &t, std::index_sequence<I...>)
{
    auto lambda = [&](auto index) -> bool
    {
        auto &elem = std::get<index.value>(t);
        elem++;
        if (elem == q)
        {
            elem = 0;
            return 0;
        }
        else
        {
            return 1;
        }
    };

    return (lambda(std::integral_constant<std::size_t, I>{}) || ...);
}

template <typename T, typename ...P>
bool increment_tuple(T q, std::tuple<P...> &t)
{
    return increment_tuple_impl(q, t, std::make_index_sequence<sizeof...(P)>{});
}

template <typename T, typename F, std::size_t MaxArity, typename ...P>
auto tabulate_impl(T q, F &&f)
{
    if constexpr (!std::is_invocable_v<F, P...>)
    {
        static_assert(sizeof...(P) < MaxArity, "Invalid function.");
        return tabulate_impl<T, F, MaxArity, P..., T>(q, std::forward<F>(f));
    }
    else
    {
        using return_type = std::invoke_result_t<F, P...>;
        std::vector<return_type> vec;
        std::tuple<P...> params{};
        do
        {
            vec.push_back(std::apply(f, params));
        }
        while (increment_tuple(q, params));
        return vec;
    }
}

template <typename T, typename F>
auto tabulate(T q, F &&f)
{
    constexpr int max_arity = 8;
    return tabulate_impl<T, F, max_arity, T>(q, std::forward<F>(f));
}

int main()
{
    auto v = tabulate(3, [](int x, int y){return x*10 + y;});

    // Prints `0 10 20 1 11 21 2 12 22`.
    for (auto x : v)
        std::cout << x << ' ';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM