[英]MetaProgramming in c++
我是C ++的新手,需要元编程帮助。 我已经检查了枚举示例,其中调用factorial<4>::value
产生24
。
我需要对代码进行修改,以便factorial<4>()
返回24
。 现在已经尝试了一段时间,并且也不知道如何在Internet上精确搜索它。 任何帮助将非常感激。 谢谢 !
这是我目前所拥有的:
template <int N>
struct factorial
{
enum { value = N * factorial<N - 1>() };
};
template <>
struct factorial<0>
{
enum { value = 1 };
};
您可以使用constexpr
函数:
template<int N>
constexpr int factorial() {
return N * factorial<N - 1>();
}
template<>
constexpr int factorial<0>() {
return 1;
}
这将使您可以致电:
factorial<4>();
并获得24
作为返回值。
或者,您可以使用隐式转换运算符operator int()
进行从struct
到int
的隐式转换:
template<int N>
struct factorial {
static const int value = N * factorial<N-1>::value;
operator int() { return value; }
};
template<>
struct factorial<0> {
static const int value = 1;
operator int() { return value; }
};
要将函数调用像函数调用一样使用,您需要使用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编译/测试]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.