Google 测试多模板 - 编译器错误

Google Test multi-templates - compiler error

正在研究的答案。但是我无法从那里的答案中编译代码。为了测试代码,我创建了一个最小的(不幸的是不工作)示例。

编辑: 我再次更新代码(考虑到 Marko Popovic 的评论):

#include <iostream>
#include "gtest/gtest.h"

template <typename A>
struct whoami { void tellme(){printf("I do not know!");} };
template <>
struct whoami<int> { void tellme(){printf("I am an integer!");} };
template <>
struct whoami<char> { void tellme(){printf("I am a character!");} };
template <>
struct whoami<bool> { void tellme(){printf("I am a boolean!");} };

template <class A, class B>
struct TypeDefs
{
  typedef typename A firstType;
  typedef typename B secondType;
};

template <class T>
class ATestExample : public testing::Test
{
protected:
  ATestExample() {}
  virtual ~ATestExample(){ }
};

typedef ::testing::Types <TypeDefs<char,char>, TypeDefs<int,int> > MyTypeList;

TYPED_TEST_CASE(ATestExample, MyTypeList);
TYPED_TEST(ATestExample, DefaultConstructor)
{
  whoami<TypeParam::firstType> info;
  info.tellme();

}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

但是还是报错:

debuging.cpp(..): error: a class or namespace qualified name is required

debuging.cpp(..): error: a class or namespace qualified name is required

debuging.cpp(..): error: nontype "gtest_TypeParam_::firstType" is not a type name
          detected during:
            implicit generation of "ATestExample_DefaultConstructor_Test<gtest_TypeParam_>::~ATestExample_DefaultConstructor_Test() [with gtest_TypeParam_=TypeDefs<char, char>]" 
gtest/gtest.h(7209): here
            instantiation of class "ATestExample_DefaultConstructor_Test<gtest_TypeParam_> [with gtest_TypeParam_=TypeDefs<char, char>]" 
gtest/gtest.h(7209): here
            implicit generation of "ATestExample_DefaultConstructor_Test<gtest_TypeParam_>::ATestExample_DefaultConstructor_Test() [with gtest_TypeParam_=TypeDefs<char, char>]" 
gtest/gtest.h(7209): here
            instantiation of class "ATestExample_DefaultConstructor_Test<gtest_TypeParam_> [with gtest_TypeParam_=TypeDefs<char, char>]" 

编辑 2: 解决方案是 "typename":

的位置排列
template <class A, class B>
struct TypeDefs
{
  typedef A firstType;
  typedef B secondType;
};

template <class T>
class ATestExample : public testing::Test
{
protected:
  ATestExample() {}
  virtual ~ATestExample(){ }
};

typedef ::testing::Types <TypeDefs<cpu,char>, TypeDefs<gpu,int> > MyTypeList;

TYPED_TEST_CASE(ATestExample, MyTypeList);
TYPED_TEST(ATestExample, DefaultConstructor)
{
  whoami<typename TypeParam::firstType> info;
  info.tellme();

}

你有两个错误。第一个是你已经命名了你的模板 struct Types,与 ::testing::Types 一起使用时会产生问题。 假设您将其重命名为 TypeDefs。然后,在测试主体中声明 typedef 时出错,因为您没有指定模板参数。您必须这样做:

typedef TypeDefs<char, int>::firstType someType;

不要在TYPED_TEST里面使用typedef,直接使用TypeParam

whoami<TypeParam::firstType> info;
info.tellme();