在GTEST (Googletest)中使用模板



我知道。标题并不完美。也许我以后会资助一个更好的标题。我有一个问题与模板GTEST。(是的,我知道。代码毫无意义。这是一个样本)。我有以下模板:

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;
};
我可以用(test success)测试代码:
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);
}

但是当我试着测试这个,链接器给我一个错误:

TEST(MY_VALUE_test, test1) {
ASSERT_EQ(8, MY_VALUE<uint8_t>::val);
ASSERT_EQ(16, MY_VALUE<uint16_t>::val);
}

链接器错误:

undefined reference to `MY_VALUE<unsigned char>::val
undefined reference to `MY_VALUE<unsigned short>::val

有人有想法吗?由于

问题在于GTEST的断言引擎需要引用。要有引用变量,需要定义:

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;

对uint16_t做同样的操作。

如果你的编译器支持c++ 17,你可以尝试在val:

中添加inline或constexpr。
template<>
struct MY_VALUE<uint8_t>{
static constexpr uint8_t val = 8;
};

谢谢你的回答。添加:

const uint8_t MY_VALUE<uint8_t>::val;

。我没有c++17支持。我不能试。

最新更新