2015-05-29 30 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'? –

相关问题