gpt4 book ai didi

c++ - C++ 循环的编译时评估

转载 作者:行者123 更新时间:2023-11-30 05:34:56 25 4
gpt4 key购买 nike

我正在尝试编写一个 C++ 循环,我希望在编译时对其进行评估。这是因为我需要使用循环变量作为模板参数来初始化一个类。在非常简单的情况下,它看起来像:

for (unsigned int i = 1; i < 8; i++) {
Vector<i> foo;
// do something with foo
}

在经历了一些类似的 StackOverflow 之后 questions ,我找到了一种递归编写静态 for 循环的方法。现在我的代码看起来像这样:

template <unsigned int i, unsigned int end>
struct static_for {
template <typename Lambda>
void operator()(const Lambda& function) const {
if (i < end) {
function(i);
static_for<start + 1, end>(function);
}
}
};

template <int N>
struct static_for<N, N> {
template <typename Lambda>
void operator()(const Lambda& function) const {
// This is just to avoid the unused variable warning - does nothing.
(void)function;
}
};

这完全符合预期。为了调用这个 static_for 循环,我可以简单地写:

static_for<0, 8>()([](int size) {
// some code here.
});

但是,问题是我仍然无法在编译时计算 i。正如我无法在 lambda 表达式中创建模板化对象:

static_for<0, 8>()([](int size) {
Vector<size> var; // does not compile as size is not a constexpr.
});

我怎样才能使这项工作?我的 static_for 循环将 i 变量作为模板参数,它在编译时可用。我希望我的 lambda 表达式也在编译时接收此参数 (size),而不是作为运行时变量传入。这将如何工作?从概念上讲,这作为一种更通用的语言功能似乎既简单又有用。

最佳答案

如果可以使用 C++14,则可以将 std::integral_constant 传递给通用 lambda 而不是 intgcc.godbolt.org example

template <unsigned int i, unsigned int end>
struct static_for {
template <typename Lambda>
void operator()(const Lambda& function) const {
if (i < end) {
function(std::integral_constant<int, i>{});
static_for<start + 1, end>(function);
}
}
};

static_for<0, 8>()([](auto size) {
Vector<decltype(size)::value> var; // does not compile as size is not a constexpr.
});

关于c++ - C++ 循环的编译时评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34036608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com