2014-03-27 36 views
-3

具有與開方模板函數(只是想嘗試一下,我知道< CMATH>不會瓶頸任何東西)C++開方使用模板,太多的模板參數

下面的代碼給出了錯誤的一些問題:太許多模板參數

namespace { 
    static const size_t ITERATIONS = 10; 
} 

template <typename T, T N> struct Sqrt { 
    static const T value = Sqrt<T, N, 1, ITERATIONS>::value; 
}; 
//Newtons method: A = (N/A + A)/2 
template <typename T, T N, T A, size_t I> struct Sqrt { 
    static const T value = Sqrt<T, N, (N/A + A)/2, I - 1>::value; 
}; 
template <typename T, T N, T A> struct Sqrt<T, N, A, 0> { 
    static const T value = A; 
}; 

感謝

+0

您的意思是有一個[可變參數模板(http://stackoverflow.com/questions/17652412/what-are-the-rules-for-the-token-in-the- context-of-variadic-template/17652683#17652683)參數列表? –

+0

我只是不確定爲什麼當我有一個接受4個參數的模板並且我還傳遞了4個參數時,出現「太多模板參數」的錯誤。 – user1843915

+0

顯示'Sqrt'的確切錯誤和用法,否則我們不會相信你。 –

回答

1

的代碼可能比你在想什麼的要簡單得多。

#include <iostream> 

template<int N, int M> struct Sqrt 
{ 
    static const int value = (Sqrt<N, M-1>::value + N/Sqrt<N, M-1>::value)/2; 
}; 

template<int N> struct Sqrt<N, 0> 
{ 
    static const int value = N/2; 
}; 


int main() 
{ 
    int y = Sqrt<200, 10>::value; 
    std::cout << "Sqrt(200): " << y << std::endl; 

    y = Sqrt<200, 20>::value; 
    std::cout << "Sqrt(200): " << y << std::endl; 

    y = Sqrt<2000, 10>::value; 
    std::cout << "Sqrt(2000): " << y << std::endl; 

    y = Sqrt<2000, 20>::value; 
    std::cout << "Sqrt(2000): " << y << std::endl; 
} 

下面列出的結果是近似值,因爲我們只處理整數值。

 
Sqrt(200): 14 
Sqrt(200): 14 
Sqrt(2000): 44 
Sqrt(2000): 44 

但是,當我試圖計算一個完美平方數的平方根時,我得到了完美的答案。

y = Sqrt<10000, 10>::value; 
    std::cout << "Sqrt(10000): " << y << std::endl; 

    y = Sqrt<10000, 20>::value; 
    std::cout << "Sqrt(10000): " << y << std::endl; 
 
Sqrt(10000): 100 
Sqrt(10000): 100