具有编译问题的简单(递归)可变参数模板"accumulate_for"函数
Simple (recursion) variadic template "accumulate_for" function with compile problems
我想编写一个可变参数模板或常量表达式,其中 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
关键字用法的详细信息,请参阅必须将"模板"和"类型名"关键字放在何处以及为什么
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 这个公式在"accumulate"时采用什么参数?