Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, repeat an input for a function multiple times

Tags:

c++

templates

Is it possible to create an input, which is than repeated N times as a parameter for the function?

An example:

#include <range/v3/view/indices.hpp>
#include <range/v3/view/cartesian_product.hpp>

template<std::size_t length, std::size_t N>
constexpr auto tensor_cartesian_product(){

    const auto cart_input1 = ranges::view::indices(length); //create input

    return ranges::view::cartesian_product(cart_input1, cart_input1, ... /* N times cart_input1 */);
}
like image 270
M.Mac Avatar asked Dec 10 '19 12:12

M.Mac


Video Answer


1 Answers

You can use pack expansion:

template<std::size_t length, std::size_t... is>
constexpr auto tensor_cartesian_product(std::index_sequence<is...>) {
    const auto cart_input = ranges::view::indices(length);
    return ranges::view::cartesian_product((is, cart_input)...);
}

template<std::size_t length, std::size_t N>
constexpr auto tensor_cartesian_product() {
    return tensor_cartesian_product<length>(std::make_index_sequence<N>{});
}

The trick here is to harness the comma operator:

The comma operator expressions have the form: E1 , E2.

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded ... . The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2. ...

The pack (is, cart_input)... will be expanded into (0, cart_input), (1, cart_input), ..., (N - 1, cart_input), and the result of evaluation of each of N terms will be cart_input.

like image 146
Evg Avatar answered Oct 19 '22 12:10

Evg