我写了一个可变参数模板,它正在执行一个函子F
正好N
次并累计结果。现在我想知道如何使这个模板能够处理目前名为id
和所需功能x, y, z
的可变数量的索引(模板)参数。递归模板函数遍历几个模板参数
我想到的是一个像下面这样的函子,它被执行,就好像你称它为三个循环一样。我也怀疑它是否可以通过参数列表来解决。
struct 3DFunctor {
template <int x, int y, int z>
static int run() {
return x*y*z;
}
};
期望的行为应该是这样的:
accum_for<3,3,3>::get<3DFunctor>();
3DFunctor::run<0,0,0>(/*args ...*/) +
3DFunctor::run<0,0,1>(/*args ...*/) +
3DFunctor::run<0,0,2>(/*args ...*/) +
3DFunctor::run<0,1,0>(/*args ...*/) +
3DFunctor::run<0,1,1>(/*args ...*/) +
3DFunctor::run<0,1,2>(/*args ...*/) +
// ..
例子:
#include <iostream>
#include <string>
struct F {
template <int id>
static int run(int val) {
return id * val;
}
};
template<unsigned int n>
struct accum1d_for {
template <class Funct, class ... ArgTypes>
static auto get(ArgTypes ... args) -> decltype(Funct::template run<0>(args ...)) {
return (
accum1d_for<n-1>::template get<Funct>(args ...) +
Funct::template run<n>(args ...)
);
}
};
template<>
struct accum1d_for<0> {
template <class Funct, class ... ArgTypes>
static auto get(ArgTypes ... args) -> decltype(Funct::template run<0>(args ...)) {
return static_cast<decltype(Funct::template run<0>(args ...))>(0);
}
};
int main()
{
std::cout << accum1d_for<10>::get<F>(2.f) << std::endl;
}
加期望的行为 – dgrat
尝试了“使用blah =”但得到了编译器错误。不确定这是否适用于函数体。 – dgrat
极少的语言版本? C++ 11,C++ 14或C++ 17? – max66