【发布时间】:2011-12-09 17:56:42
【问题描述】:
事实上,我想评估 2 个数组的点积。当我尝试这个时
template <int N, typename ValueType>
struct ScalarProduct {
static ValueType product (ValueType* first, ValueType* second) {
return ScalarProduct<N-1, ValueType>::product(first + 1, second + 1)
+ *first * *second;
}
};
template <typename ValueType>
struct ScalarProduct<0, ValueType> {
static ValueType product (ValueType* first, ValueType* second) {
return 0;
}
那么在运行时计算的时间少于编译期间的时间
【问题讨论】:
-
这个问题有点不清楚。您询问有关使用元编程展开循环的问题,但我没有看到您尝试展开的循环。请澄清一下?
-
@JohnDibling:他显然是指递归调用,这是运行时循环的一种替代方法。
-
你的方法有什么问题吗?你的代码对我来说很好。
-
我想知道这种方式比运行时循环慢是否正常
-
@reinearthed :是的,这很正常,因为您的函数不是尾递归的。如果将其设为尾递归,它可能与运行时
for循环相同。
标签: c++ metaprogramming