首页 > 解决方案 > C++中模板的复杂使用

问题描述

我遇到了一段关于模板的代码:

展开器.h

template <int It, int End> struct unroller {
    template <typename Action> static void step(const Action &action) {
        action(std::integral_constant<int, It>());
        unroller<It + 1, End>::step(action);
    }
};

template <int End> struct unroller<End, End> {
    template <typename Action> static void step(const Action &) {}
};

显示如何调用它的代码片段:

constexpr int NUM_ROWS = 2;
constexpr int NUM_COLS = 2;
int input_idx = 0;
for (int pass = 0; pass < num_passes; pass++) {
    unroller<0, NUM_ROWS>::step([&input_idx, input_accessor](auto i_idx) {
    constexpr int i = i_idx.value;

        unroller<0, NUM_COLS>::step([&input_idx, input_accessor](auto j_idx) {
        constexpr int j = j_idx.value;

            ProducerToConsumerPipeMatrix::pipe_at<i, j>::write(input_accessor[input_idx++]);
        });
    });
} 

问题:

  1. template <typename Action> static void step(const Action &action)是功能模板吗?
  2. 什么是action(std::integral_constant<int,It>());?我认为动作是通过引用传递的。但是,我真的不明白。
  3. 我不明白它调用的方式unroller<0, NUM_ROWS>::step([&input_idx, input_accessor](autoi_idx)。我的理解是尖括号里的<>应该是数据类型。在这种情况下,它传递值。此外, ::step 是什么?那么,为什么它可以在 step(...)> 中传递 2 个参数

我是 C++ 新手。有人可以用简单的方式解释吗?

标签: c++templates

解决方案


我认为您可能需要从头开始学习模板。

  1. 是的。这是一个典型的函数模板
  2. 不,它是按值传递的,至少在您的示例中是按值传递的。
[&input_idx, input_accessor](auto j_idx) {
        constexpr int j = j_idx.value;

            ProducerToConsumerPipeMatrix::pipe_at<i, j>::write(input_accessor[input_idx++]);
        });

这个 lambda 作为其参数传递给高阶函数step,稍后它将接收一个std::integral_constant<int, It>prvalue 临时作为 lambda 的参数。

std::integral_constant<int,It>()构造一个临时对象std::integral_constant<int, It>,参见:https ://en.cppreference.com/w/cpp/types/integral_constant

  1. 这不是两个参数,而是 lambda 捕获,请参见:https ://en.cppreference.com/w/cpp/language/lambda

模板的参数不需要是类型,请参见:https ://en.cppreference.com/w/cpp/language/templates#Syntax


推荐阅读