[英]Use Template in GTEST (Googletest)
I know.我知道。 The headline is not perfekt.标题并不完美。 Perhaps I fund a better Headline later.也许我稍后会资助一个更好的标题。 I have a Problem with GTEST with template.我对带有模板的 GTEST 有疑问。 (Yes I know. The code make no sense. It is a sample). (是的,我知道。代码没有意义。这是一个示例)。 I have the following template:我有以下模板:
template<typename T>
struct MY_VALUE{};
template<>
struct MY_VALUE<uint8_t>{
static const uint8_t val = 8;
};
template<>
struct MY_VALUE<uint16_t>{
static const uint16_t val = 16;
};
I can test the code with (test sucess):我可以使用(测试成功)测试代码:
TEST(MY_VALUE_test, test) {
uint32_t var8 = MY_VALUE<uint8_t>::val;
ASSERT_EQ(8, var8);
uint32_t var16 = MY_VALUE<uint16_t>::val;
ASSERT_EQ(16, var16);
}
But when i try to test this, the LINKER give me an error:但是当我尝试对此进行测试时,LINKER 给我一个错误:
TEST(MY_VALUE_test, test1) {
ASSERT_EQ(8, MY_VALUE<uint8_t>::val);
ASSERT_EQ(16, MY_VALUE<uint16_t>::val);
}
Linker error: Linker 错误:
undefined reference to `MY_VALUE<unsigned char>::val
undefined reference to `MY_VALUE<unsigned short>::val
anyone an idea:) Thanks任何人的想法:) 谢谢
The problem is with the fact that assertion engine of GTEST requires reference.问题在于 GTEST 的断言引擎需要参考。 To have reference - variable needs to be defined:要获得参考 - 需要定义变量:
template<>
struct MY_VALUE<uint8_t>{
static const uint8_t val = 8;
};
// this line is missing
// Note: do not put it in header - if you have multiple files project
const uint8_t MY_VALUE<uint8_t>::val;
Do the same for uint16_t.对 uint16_t 执行相同的操作。
IF you have compiler supporting C++17 - you might try to just add inline or constexpr to val:如果您有支持 C++17 的编译器 - 您可以尝试将inline或 constexpr 添加到 val:
template<>
struct MY_VALUE<uint8_t>{
static constexpr uint8_t val = 8;
};
Thanks, your answer helps.谢谢,你的回答有帮助。 Adding:添加:
const uint8_t MY_VALUE<uint8_t>::val;
works.作品。 I have no c++17 support.我没有 c++17 支持。 I cant try this.我不能试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.