[英]variadic template recursion with sizeof…, but compile error: no matching function
[英]Simple (recursion) variadic template “accumulate_for” function with compile problems
我想编写一个可变参数模板或const表达式,其中1)执行N
次模板函子,2)累加结果。 我写了一个小例子,当我将要执行的功能移入模板函子后,实际上却使编译失败。 我有接近解决方案的感觉,但也许我错了。
#include <iostream>
#include <string>
struct F {
template <int id>
static int run(int val) {
return id * val;
}
};
template<unsigned int n>
struct accumulate_for
{
template <class Funct>
static int get(int val) {
return
(
accumulate_for<n-1>::get(val)
+
Funct::run<n>(val)
);
}
};
template<>
struct accumulate_for<0>
{
template <class Funct>
static int get(int val) {
return 0;
}
};
int main()
{
std::cout << accumulate_for<3>::get<F>(1) << std::endl;
}
accumulate_for<n>::get
是成员函数模板,因此在调用它时必须指定模板参数。
您需要使用template关键字来指示get
和run
(都是从属名称)是模板。
例如
template<unsigned int n>
struct accumulate_for
{
template <class Funct>
static int get(int val) {
return
(
accumulate_for<n-1>::template get<Funct>(val)
// ~~~~~~~~ ~~~~~~~
+
Funct::template run<n>(val)
// ~~~~~~~~
);
}
};
有关template
关键字用法的更多信息,请参阅在何处以及为什么必须将“ template”和“ typename”关键字放在哪里?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.