假设我正在为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/