是否可以使函数对于常量参数或变量参数的行为不同
Is it possible to make a function behave differently for constant argument or variable argument?
例如,factorial(n),如果参数是一个常量(表达式),那么结果是确定性的,并且可以在编译时完成(通过使用模板元编程)。
是否可以只编写单个函数,以便无论何时调用它,如果参数是常量,那么结果将在编译时计算,如果它是一个变量,那么它将在运行时进行计算?
这正是constexpr
函数存在的目的。 constexpr
功能是在 C++11 中引入的。当使用可在编译时计算的常量表达式调用时,它们往往在编译时计算(有时您可以强制这样做)。但是,一般来说,不可能提供保证。否则,它们将在运行时计算(您可以像在运行时计算常量或非常量参数的常规函数一样调用它们)。
除了缺乏编译时计算的保证之外,constexpr
函数还有约束:它必须只包含一个 return 语句,所以如果你正在寻找一种执行任何复杂计算的方法,这将不符合你的需求。尽管如此,constexpr
函数可能是最接近您正在寻找的功能。
既然您提到了 factorial()
函数的示例,那么使用 constexpr
函数会如下所示:
#include <iostream>
using namespace std;
constexpr int factorial(int n)
{
return (n == 0) ? 1 : factorial(n - 1);
}
int foo()
{
int result = 1;
// do some processing...
return result;
}
int main()
{
int v[factorial(5)]; // Evaluated at compile-time
cout << factorial(foo()); // Evaluated at run-time
}
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 扩展可变参数模板中的变量名称
- 在类构造函数中定义结构变量的参数
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 存储稍后要转发的变量参数
- C++具有模板成员变量的类. 和参数内存输出
- 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- 为变量模板的每个参数调用模板函数
- 具有推导参数的模板函数指针数组变量
- 函数参数变量总是需要 & 或 * 运算符吗?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 如何在函数中使用非参数变量?
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 基于不断变化的参数/变量的XML get值
- cocos2d-x v3 CallFunc作为参数/变量如何
- 在编译时使用c++元编程中的运行时参数(变量)
- 我可以返回一个非参数变量吗?