我是c++新手,需要元编程方面的帮助。我已经检查了枚举示例,其中调用factorial<4>::value生成24。
我需要的是对代码进行修改,以便factorial<4>()返回24。已经尝试了相当一段时间了,也不知道如何在互联网上准确地搜索它。任何帮助都将不胜感激。谢谢!
以下是我目前所拥有的:
template <int N>
struct factorial
{
enum { value = N * factorial<N - 1>() };
};
template <>
struct factorial<0>
{
enum { value = 1 };
};发布于 2014-06-16 05:07:10
要像函数调用一样使用函数调用,需要使用constexpr (C++11的一个新添加项)。注意,当您使用它时,您根本不需要使用模板。虽然有一些限制,但基本语法是普通函数的语法:
int constexpr fact(int x) { return x == 0 ? 1 : x * fact(x - 1); }不过,这仍然是在编译时计算的。例如,如果要使用它指定数组的大小,可以这样做:
int main(){
int array[fact(5)];
}同样,您可以在switch语句中使用这样的结果作为一个大小写:
#include <iostream>
#include <cstdlib>
int constexpr fact(int x) { return x == 0 ? 1 : x * fact(x - 1); }
int main(int agc, char **argv){
switch (std::atoi(argv[1])) {
case fact(1) :
case fact(2):
case fact(3):
case fact(4):
case fact(5):
std::cout << "You entered a perfect factorial";
break;
default:
std::cout << "I'm not sure about that";
}
}用gcc 4.8.1编译/测试
https://stackoverflow.com/questions/24235232
复制相似问题