具有编译问题的简单(递归)可变参数模板"accumulate_for"函数

Simple (recursion) variadic template "accumulate_for" function with compile problems

本文关键字:参数 accumulate 函数 for 变参 问题 编译 简单 递归      更新时间:2023-10-16

我想编写一个可变参数模板或常量表达式,其中 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; 
}
  1. >accumulate_for<n>::get是一个成员函数模板,因此在调用它时必须指定模板参数。

  2. 您需要使用 template 关键字来指示getrun(都是从属名称(是模板。

例如

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关键字用法的详细信息,请参阅必须将"模板"和"类型名"关键字放在何处以及为什么