简体   繁体   English

使用模板功能的C ++模板元编程

[英]C++ template meta programming using template functions

I have been lately been learning template meta programming in C++. 我最近一直在学习C ++中的模板元编程。 After checking calculating factorials example, was wondering if the same thing could be done only with template functions rather than template classes. 在检查了计算阶乘的示例之后,想知道是否只能使用模板函数而不是模板类来完成相同的事情。 My first attempt is shown below 我的第一次尝试如下所示

#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;

}

But I get the following compiler errors 但是我得到以下编译器错误

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

Can I do such template metaprogramming using template functions? 我可以使用模板功能进行这样的模板元编程吗? Is this allowed ? 可以吗?

As stated by tobi303 in the comments, using just (t) as a parameter list of a function, where t is not a type name, makes no sense. 如tobi303在评论中所述,仅将(t)用作函数的参数列表(其中t不是类型名称)是没有意义的。

Since int t is a template parameter, not a regular parameter, it should only be present in the template parameters list (between the < and > angle brackets), and not in the function parameters list (between the ( and ) parenthesis). 由于int t是模板参数,而不是常规参数,因此它只能出现在模板参数列表中(在<>尖括号之间),而不能出现在功能参数列表中( ()括号之间)。 Template parameters must also be passed as such, ie multiply<5>() instead of multiply(5) in your code. 模板参数也必须这样传递,即在代码中multiply<5>()而不是multiply(5)

You could use something like: 您可以使用类似:

#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;
}

Note also that I've added constexpr (C++11 and later) to always be able to evaluate these functions at compile-time. 还要注意,我添加了constexpr (C ++ 11和更高版本),以便始终能够在编译时评估这些函数。 However, the compiler is not forced to evaluate these at compile-time instead of run-time, and you might still end up with the run-time overhead. 但是,编译器没有被迫在编译时而不是运行时进行评估,并且您可能最终仍会遇到运行时开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM