2017-05-08 32 views
-4

我想知道模板元編程解決方案找到使用遞歸Euclid算法的兩個數字的GCD的問題,下面給出供您參考。在C++中使用模板元編程,找到兩個整數的GCD

function gcd(a, b) 
    if b = 0 
     return a; 
    else 
     return gcd(b, a mod b); 

任何幫助將不勝感激!

+7

我投票結束這個問題作爲題外話,因爲它是一個代碼請求,沒有顯示的努力提供解決問題的代碼。 OP將通過制定解決方案來學習更多東西,而不是用勺子餵食。 – Peter

回答

2

這樣的事情?

#include <utility> 
#include <iostream> 

template<int a, int b> struct gcd 
{ 
    static constexpr auto value = gcd<b, a % b>::value; 
}; 

template<int a> 
struct gcd<a, 0> 
{ 
    static constexpr auto value = a; 
}; 

int main() 
{ 
    auto x = gcd<10,5>::value; 

    std::cout << x << std::endl; 
} 
+0

在專業版中,爲什麼不說struct gcd ? –

+1

@VarunRao因爲這不是如何使用模板參數。你不寫'printf(const char *「我的文本」);' – Caleth

+0

@VarunRao試試看。 –