c++ - C++模板和参数化的Google测试

标签 c++ googletest

假设我正在为class_a类编写模板:

bool test_success;
template <uint32_t len>
class class_a
{
    uint32_t do_something(void)
    {
        return len+1;
    }
};
我想用一系列不同的len值测试该类,因此我正在进行参数化测试。
现在,编写测试装置时出现了问题:
class test_classa : public::testing::TestWithParam<    uint32_t    >
{
    void SetUp() override
    {
        test_success = false;
        // constexpr uint32_t a_len = GetParam(); //compiler error 1 (See below)
        // const uint32_t a_len = GetParam(); //compiler error 2 (See below)
        constexpr uint32_t a_len = 5; //Works! But that's not using the test parameter!
        class_a<a_len> a_test;
        if (a_test.do_something() == (a_len+1))
        {
           test_success = true;
        }
    }

    void TearDown() override
    {

    }
};
我的其余代码如下:
TEST_P(test_classa, test_classa) {
    EXPECT_EQ (test_success, true);
}

INSTANTIATE_TEST_SUITE_P(
        class_a,
        test_classa,
        ::testing::Values(
            10,
            20
            ));
那么有人可以帮助我完成这项工作吗?可能吗?
编辑:
根据要求,这是编译错误:
(1)constexpr变量'a_len'必须由常量表达式初始化
(2)非类型模板参数不是常量表达式

最佳答案

至少您错误地导出了该类。尝试推导

class test_classa : public testing::TestWithParam<    uint32_t    >
编辑
在提供了详细信息之后,我看到您正在将一个函数调用分配给constexpr,如果您的函数也是constexpr的话,这可能会起作用,因为constexpr是在编译时解析的。我相信编译器消息包括类似的消息,例如“函数必须是constexpr”。
对于第二种情况,我不了解有关GetParam函数的详细信息,并且由于您没有包括整个编译器消息,我相信仔细阅读它会提示您在哪里可以找到要解决的问题。
如果到那时仍找不到,请更新问题,并在此处发布问题时尝试提供尽可能多的信息。
编辑2
现在我看到了第二个问题。它正在尝试使用const变量实例化模板。这是不可能的,因为const variable的值是在运行时获取的,并且模板是在编译期间实例化的。你不能做这样的事情。

关于c++ - C++模板和参数化的Google测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63309831/

相关文章:

linux - QApplication 之后的清理

c++ - Google Test Main 没有声明 main

c++ - 在 Mac 上构建 Googletest 时出现链接错误(命令行)

c++ - 检测 TIFF 图像中每个像素的位数

c++ - 什么是 C++ 中的 std::invoke?

c++ - bazel 测试与直接执行

c++ - 编译 Google Test 时出现 g++ fatal error

C++ 重载 >> 运算符基于 >> 的哪一侧具有不同的交互

c++ - 用两个参数重载 operator bool 是什么意思?

c++ - boost tribool 使用率