【发布时间】:2015-12-02 06:52:08
【问题描述】:
我正在尝试编写一个我想在编译时评估的 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),而不是作为运行时变量传入。这将如何工作?从概念上讲,这作为一种更通用的语言功能似乎也很简单且有用。
【问题讨论】:
-
问题是 lambda 不是
constexpr表达式。如果您改用constexpr函数,它可能会起作用。 -
问题在于将 constexpr 函数模板作为可调用对象传递。知道代码的用途吗?
-
您可以尝试将 std::integral_constant 传递给 lambda 而不是 int。使用带有“auto”的通用 C++14 lambda
标签: c++ lambda compilation