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

标签 c++ templates

是否可以创建一个输入,作为函数的参数重复 N 次?

一个例子:

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

最佳答案

您可以使用 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>{});
}

这里的诀窍是利用 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. ...



包装(is, cart_input)...将扩展为 (0, cart_input), (1, cart_input), ..., (N - 1, cart_input) ,以及N中每一个的评估结果条款将是 cart_input .

关于C++,多次重复一个函数的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266935/

相关文章:

c++ - 获取当前小时 unix 时间戳

c++ - 我可以使用私有(private)嵌套结构编写仿函数吗?

c++ - "Reading"POD 预增量结果不会产生未定义的行为。为什么呢?

django - 高级 Django 模板逻辑

c++ - 将模板函数转换为非模板类​​?

css - 在 Ember 中更改现有模板的背景颜色

c++ - 计算每个单词在文件中出现的次数

c++: 为什么使用 .open("a:

具有 const 类型或简单类型参数的方法的 C++ 模板函数

Java - 从字符串中解析枚举的通用函数