gpt4 book ai didi

c++ - 使用必须变化的 const 模板参数测试基于模板的类

转载 作者:行者123 更新时间:2023-11-28 02:26:19 25 4
gpt4 key购买 nike

我正在开发一个基于模板的库来支持定点整数,我想出了这个类,现在我必须针对 INT_BITSFRAC_BITS 的各种值来测试它.但由于它们是 const(出于某种原因它们必须如此),我无法在循环中使用变量 INT_BITS 初始化对象,因此它正在测试这个图书馆很难。

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;
};

我尝试了很多提到的技巧 here , herehere .我尝试使用 const intconst_caststd::vector 但似乎没有任何效果。

我想知道,对于大型测试值,您如何测试模板参数为 const 的此类库?

最佳答案

您可以使用模板元编程模拟 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>

您可以通过搜索“for loop using template metaprogramming”在网络上找到更多信息。

关于c++ - 使用必须变化的 const 模板参数测试基于模板的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com