mardi 18 février 2020

Capture std::array in lambda

I was trying to test some simple C-style sort functions. In the driver program, I wrote something like this:

int main()
{
    std::array<int, 8> A = { 1, 0, 4, 5, 7, 2, 9, 3 };
    auto lambda = [&A](const std::function<void(int *A, int n)> &sorting_alg) {
        int n = A.size();
        sorting_alg(A.data(), n);
        std::cout << "=> ";
        print(A.data(), n);
        std::cout << std::endl;
    };

    auto do_bubble_sort = std::bind(lambda, bubble_sort);
    auto do_selection_sort  = std::bind(lambda, selection_sort);
    auto do_insertion_sort  = std::bind(lambda, insertion_sort);

    std::cout << "Bubble Sort :" << std::endl;
    do_bubble_sort();
    std::cout << "Selection Sort :" << std::endl;
    do_selection_sort();
    std::cout << "Insertion Sort :" << std::endl;
    do_insertion_sort();

    return 0;
}

I had the bind code, to which I could pass A to copy, but it confines my lambda to size=8, which I want to avoid. Is it possible to achieve this without using something like std::vector, etc? As soon I change capture method of A to value-capture, it doesn't compile anymore. I wanted to use copies for the array, to test all sorting functions. Why can't I capture std::array by value? Why then size-inference works for reference case?

Aucun commentaire:

Enregistrer un commentaire