c++ - 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++]);
});
});
}
问题:
template <typename Action> static void step(const Action &action)
是功能模板吗?- 什么是
action(std::integral_constant<int,It>());
?我认为动作是通过引用传递的。但是,我真的不明白。 - 我不明白它调用的方式
unroller<0, NUM_ROWS>::step([&input_idx, input_accessor](autoi_idx)
。我的理解是尖括号里的<>应该是数据类型。在这种情况下,它传递值。此外, ::step 是什么?那么,为什么它可以在 step(...)> 中传递 2 个参数
我是 C++ 新手。有人可以用简单的方式解释吗?
解决方案
我认为您可能需要从头开始学习模板。
- 是的。这是一个典型的函数模板
- 不,它是按值传递的,至少在您的示例中是按值传递的。
[&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
- 这不是两个参数,而是 lambda 捕获,请参见:https ://en.cppreference.com/w/cpp/language/lambda
模板的参数不需要是类型,请参见:https ://en.cppreference.com/w/cpp/language/templates#Syntax
推荐阅读
- lua - 为什么这个协程会停止主线程?
- python-3.x - 无法在 python 可执行文件中执行 VBoxManage 命令(使用 pyinstaller 创建)
- macos - 是否可以在 Mac OS X 中使用 mac_policy_ops 隐藏 vnode
- android - Android Studio 角半径/高程和阴影颜色
- python - 如何使用 python 将烧瓶 html 中的数据库 id 传递到 post 表单中
- java - 简单 JDA bot 上未解决的编译问题
- react-native - Redux Saga 阻塞
- java - Spring datajpa 分页查询优化
- apache-flink - 通过与广播流的连接后,keyedstream的输出流是否被keyed?
- multithreading - 为什么线程锁不会使多线程变得无用?