2013-08-14 14 views
5

Per calcolare fattoriale posso usare:ricorsivo template metaprogrammazione

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

template<> struct factorial<1> { enum { value = 1 }; }; //base Case 

e quindi può essere utilizzato come seguire

x=factorial<8>::value;

Quindi, è possibile ottenere simili modello ricorsivo per

unsigned Log2(unsigned n, unsigned p = 0) { 
    return (n <= 1) ? p : Log2(n/2, p + 1); 
} 

Posso pensare a questo:

template<int N,unsigned int P=0> struct Log2 
    { enum { value = Log2<N/2,P+1>::value }; }; 

Ma non so come impostare un caso base.

template<> struct Log2<0,???> { enum { value = ???? }; }; 

Qualche idea?

risposta

8

Si potrebbe utilizzare la specializzazione parziale

template <unsigned p> 
struct Log2<0, p> { enum { value = p }; }; 

template <unsigned p> 
struct Log2<1, p> { enum { value = p }; }; 

In C++ 11, invece di creare un modello, è possibile attivare la funzione di constexpr invece.

constexpr unsigned Log2(unsigned n, unsigned p = 0) { 
    return (n <= 1) ? p : Log2(n/2, p + 1); 
} 

std::array<int, Log2(256)> x {{1, 2, 3, 4, 5, 6, 7, 8}}; 
//    ^^^^^^^^^ Just a compile-time function call. 
+0

grazie, penso che dovrebbe essere 'value = p-1'? – P0W

+0

@ P0W: Beh, sto solo usando la tua implementazione che restituisce 'p' quando' n <= 1'. – kennytm

+0

Sì, grazie – P0W

Problemi correlati