2015-05-29 32 views
0

我正在開發一個基於模板的庫來支持定點整數,我想出了這個類,現在我必須測試它的各種值INT_BITSFRAC_BITS。但由於它們是const(並且它們必須如此出於某種原因),所以我無法在循環中初始化變量爲INT_BITS的對象,因此它正在對此庫進行測試非常困難。
基於測試模板的類與const模板參數必須改變

template<int INT_BITS, int FRAC_BITS> 
struct fp_int 
{ 
    public: 
      static const int BIT_LENGTH = INT_BITS + FRAC_BITS; 
      static const int FRAC_BITS_LENGTH = FRAC_BITS; 
    private: 
      // Value of the Fixed Point Integer 
      ValueType stored_val; 
}; 

我嘗試了很多花樣提到hereherehere。我試圖使用const intconst_caststd::vector,但似乎沒有任何工作。

我在想,如何測試這樣的庫,其中模板參數是一個大的測試值的常量?

+0

另一種選擇是編寫一個輸出另一個C++程序的程序,該程序爲各種值創建對象 –

回答

2

您可以使用模板元編程來模擬for循環。

#include <iostream> 

typedef int ValueType; 

template<int INT_BITS, int FRAC_BITS> 
struct fp_int 
{ 
    public: 
     static const int BIT_LENGTH = INT_BITS + FRAC_BITS; 
     static const int FRAC_BITS_LENGTH = FRAC_BITS; 
    private: 
     // Value of the Fixed Point Integer 
     ValueType stored_val = 0; 
}; 

template <unsigned int N> struct ForLoop 
{ 
    static void testFpInt() 
    { 
     std::cout << "Testing fp_int<" << N << ", 2>\n"; 
     fp_int<N, 2> x; 
     // Use x 

     // Call the next level 
     ForLoop<N-1>::testFpInt(); 
    } 
}; 

// Terminating struct. 
template <> struct ForLoop<0> 
{ 
    static void testFpInt() 
    { 
     std::cout << "Testing fp_int<" << 0 << ", 2>\n"; 
     fp_int<0, 2> x; 
     // Use x 
    } 
}; 

int main() 
{ 
    ForLoop<10>::testFpInt(); 
    return 0; 
} 

輸出

Testing fp_int<10, 2> 
Testing fp_int<9, 2> 
Testing fp_int<8, 2> 
Testing fp_int<7, 2> 
Testing fp_int<6, 2> 
Testing fp_int<5, 2> 
Testing fp_int<4, 2> 
Testing fp_int<3, 2> 
Testing fp_int<2, 2> 
Testing fp_int<1, 2> 
Testing fp_int<0, 2> 

您可以通過搜索「爲循環使用模板元編程」在網絡上找到更多信息。

+0

非常感謝!如果我是正確的,我需要寫兩個終止的情況下,如果我做一個循環來改變'INT_BITS'和'FRAC_BITS'? –

相關問題