为什么我不能在非常量表达式上使用此模板阶乘函数?
Why can't I use this Template factorial function on a non-constant expression?
我正在尝试熟悉模板元编程
请考虑以下代码,它使用基本的介绍性阶乘 模板功能在许多在线模板教程中找到。
#include <iostream>
template <int N> struct Factorial {
static const int result = N * Factorial<N-1>::result;
};
template <> struct Factorial<0> {
static const int result = 1;
};
int main() {
int tmp;
std::cin >> tmp;
static const int tmpc = tmp;
std::cout << Factorial<tmpc>::result << "n";
return 0;
}
如果我tmpc=10
设置为编译时常量,该示例将完美运行。但是如果 tmpc = tmp 那么,我得到编译错误
templates.cpp: In function ‘int main()’:
templates.cpp:30:29: error: the value of ‘tmpc’ is not usable in a constant expression
std::cout << Factorial<tmpc>::result << "n";
^~~~
templates.cpp:29:23: note: ‘tmpc’ was not initialized with a constant expression
static const int tmpc = tmp;
^~~~
templates.cpp:30:33: error: the value of ‘tmpc’ is not usable in a constant expression
std::cout << Factorial<tmpc>::result << "n";
^
templates.cpp:29:23: note: ‘tmpc’ was not initialized with a constant expression
static const int tmpc = tmp;
^~~~
templates.cpp:30:33: note: in template argument for type ‘int’
std::cout << Factorial<tmpc>::result << "n";
这是否意味着,我只能在编译时常量表达式上使用模板化函数?!!!
我的理解哪里出错了?
这是否意味着,我只能在编译时使用模板化函数 常量表达式?!!!
注意术语。模板函数可以使用运行时值,但元函数不能,因为它(根据定义(在编译时计算。
函数模板更普通一些:
template <typename T>
void f(T arg) { /*...*/ }
调用 f(( 将导致对所使用的每个唯一类型进行不同的 f(( 实例化,但它仍然是采用运行时值的运行时函数。
对于元函数,参数本身是模板参数,模板参数不能是运行时值。
我只能在编译时常量表达式上使用模板化函数?
是的。模板在编译时进行评估。
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 为什么我在C++阶乘函数中出现编译错误?
- 阶乘函数只返回C++中输入的答案
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- 返回阶乘C++的递归函数
- C++ 中是否有任何内置阶乘函数?
- 为什么叮当使我的简单阶乘函数过于复杂
- 3 函数加主函数 C 程序计算和显示阶乘
- 带有自定义数字的阶乘函数不起作用
- 阶乘函数不适用于大数
- 自定义阶乘函数未按预期工作
- 递归阶乘函数在"22!"上产生不正确的结果
- 为什么这个阶乘函数返回int而不是double
- 在C++中跟踪递归阶乘函数
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- 记忆化的递归阶乘函数
- 了解如何在c++中使用阶乘函数
- 为什么阶乘递归函数比普通阶乘函数效率低
- 有数据类型问题的c++阶乘函数
- 如何在c++中实现阶乘函数并进行正确的错误处理