簡體   English   中英

C ++中的元編程

[英]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()進行從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; }
};

現場演示

要將函數調用像函數調用一樣使用,您需要使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM