简体   繁体   English

C ++中的元编程

[英]MetaProgramming in c++

I am new to c++ and need help with metaprogramming. 我是C ++的新手,需要元编程帮助。 I have checked out the enum example wherein the call factorial<4>::value yields 24 . 我已经检查了枚举示例,其中调用factorial<4>::value产生24

What I need is a modification to the code so that factorial<4>() returns 24 . 我需要对代码进行修改,以便factorial<4>()返回24 Have been trying it for quite some time now and do not know how to exactly search for it on the internet too. 现在已经尝试了一段时间,并且也不知道如何在Internet上精确搜索它。 Any help would be much appreciated. 任何帮助将非常感激。 Thank you ! 谢谢 !

Here is what I have at the moment: 这是我目前所拥有的:

template <int N>
struct factorial
{
    enum { value = N * factorial<N - 1>() };
};

template <>
struct factorial<0>
{
    enum { value = 1 };
};

You can use a constexpr function: 您可以使用constexpr函数:

template<int N>
constexpr int factorial() {
    return N * factorial<N - 1>();
}

template<>
constexpr int factorial<0>() {
    return 1;
}

Live demo 现场演示

This will allow you to call: 这将使您可以致电:

factorial<4>();

and get 24 as a returned value. 并获得24作为返回值。


Alternatively you can use the implicit conversion operator operator int() to perform an implicit conversion, of the struct to int : 或者,您可以使用隐式转换运算符operator int()进行从structint的隐式转换:

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

Live demo 现场演示

To just use the function call like a function call, you need to use constexpr (a new addition to C++11). 要将函数调用像函数调用一样使用,您需要使用constexpr (C ++ 11的新增功能)。 Note that when you do use this, you do not need to use a template at all though. 请注意,当使用这个,你不需要使用模板都不过。 Though there are some limitations, the basic syntax is that of a normal function: 尽管有一些限制,但是基本语法是普通函数的语法:

int constexpr fact(int x) { return x == 0 ? 1 : x * fact(x - 1); }

This is still computed at compile time though. 不过,这仍在编译时计算。 For example, if you wanted to use it to specify the size of an array, you could do so: 例如,如果您想使用它来指定数组的大小,则可以这样做:

int main(){
    int array[fact(5)];
}

Likewise, you can use such a result as a case in a switch statement: 同样,您可以在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";
    }
}

[compiled/tested with gcc 4.8.1] [使用gcc 4.8.1编译/测试]

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

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