使用模板函数的 C++ 模板元编程

标签 c++ templates recursion

我最近一直在学习 C++ 中的模板元编程。 在检查了计算阶乘示例之后,想知道是否可以仅使用模板函数而不是模板类来完成同样的事情。 我的第一次尝试如下所示

#include <stdio.h>
#include <iostream>

using namespace std;

template <int t>
int multiply(t)
{
    return (multiply(t-1) * t);
}

template <>
int multiply(1)
{
    return 1;
}

int main () {
    cout << multiply(5) << endl;
    return 0;

}

但是我得到以下编译器错误

temp.cpp:7: error: template declaration of 'int multiply'
temp.cpp:14: error: expected ';' before '{' token
temp.cpp: In function 'int main()':
temp.cpp:19: error: 'multiply' was not declared in this scope

我可以使用模板函数进行这样的模板元编程吗?这是允许的吗?

最佳答案

正如 tobi303 在评论中所述,仅使用 (t) 作为函数的参数列表,其中 t 不是类型名称,是没有意义的。

由于 int t 是模板参数,而不是常规参数,它应该只出现在模板参数列表中(在 <> 尖括号之间),而不是在函数参数列表中(在 () 括号之间) .模板参数也必须这样传递,即 multiply<5>() 而不是代码中的 multiply(5)

你可以使用类似的东西:

#include <iostream>

using namespace std;

template <int t>
constexpr int multiply() {
    return multiply<t - 1>() * t;
}

template <>
constexpr int multiply<1>() {
    return 1;
}

int main () {
    cout << multiply<5>() << endl;
    return 0;
}

另请注意,我添加了 constexpr(C++11 及更高版本)以便始终能够在编译时计算这些函数。但是,编译器不会强制在编译时而不是在运行时评估这些,您可能仍会以运行时开销告终。

关于使用模板函数的 C++ 模板元编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798798/

相关文章:

c++ - 在 SetUnhandledExceptionFilter 的处理程序中如何打印堆栈跟踪?

c++ - 为 iPhone 构建时出现 GCC 链接器错误

c++ - 当模板参数包含非静态成员名称时,是否需要 'typename'?

c++ - C++17和C++20在模板友元函数中一元和二元运算符的区别

c++ - 为指针或标量优化函数

javascript - 如何在 JavaScript 对象循环内递归聚合值?

c++ - 使用 operator= 从对象分配 std::string

c++ - 编译器在哪里找到 `` printf``?

exception - 不断收到错误信息 "Arguments are not sufficiently instantiated"不明白为什么

c - 使用分治法的矩阵乘法