简体   繁体   English

C++,多次重复一个函数的输入

[英]C++, repeat an input for a function multiple times

Is it possible to create an input, which is than repeated N times as a parameter for the function?是否可以创建一个输入,作为函数的参数重复 N 次?

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 */);
}

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 .逗号运算符表达式的形式为: E1 , E2

In a comma expression E1, E2 , the expression E1 is evaluated, its result is discarded ... .在逗号表达式E1, E2 ,表达式E1被计算,其结果被丢弃......。 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 .逗号表达式结果的类型、值和值类别正是第二个操作数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 .(is, cart_input)...将展开为(0, cart_input), (1, cart_input), ..., (N - 1, cart_input)N项中每一项的评估结果将是cart_input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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