我最近一直在学习 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 及更高版本)以始终能够在编译时评估这些函数。但是,编译器不会被迫在编译时而不是运行时评估这些,并且您最终可能仍会产生运行时开销。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句