0

在 C++ 中使用 Trompeloeil 模拟单元测试时,如何使用 anunordered_map作为返回类型?

// This example works fine
// return type is void, my_function takes no arguments 
MAKE_MOCK0(my_function, void(), override);


// This is what I'm trying to do but fails
MAKE_MOCK0(my_function, std::unordered_map<std::string, int>(), override);

Visual Studio 给出以下 IntelliSense 错误,

  • C2976 - std::unordered_map: 模板参数太少
  • C2955 - std::unordered_map:使用类模板需要模板参数列表
  • C2923 - trompeloeil::param_list:std::_Hash<_Traits::size>不是参数类型的有效模板类型参数T
  • C2143> -之前缺少语法错误;
  • C2955 -trompeloeil::param_list使用类模板需要模板参数列表
  • C2338 - 函数签名没有 0 个参数
  • C3203 -非专业unordered_map类不能用作模板参数“Sig”的模板参数,需要一个真实类型
  • C4346 -std::unordered_map::type从属名称不是类型
  • C2923 - trompeloeil::identity_type:std::unordered_map::type不是参数类型的有效模板类型参数T
  • C3203 -未专门化unordered_map的类不能用作模板参数“T”的模板参数,应为真实类型
4

1 回答 1

1

模板化的返回类型需要包装在(...). 这在:Q. 为什么我不能模拟返回模板的函数?

// Bad
MAKE_MOCK0(my_function, std::unordered_map<std::string, int>(), override);

// Good
MAKE_MOCK0(my_function, (std::unordered_map<std::string, int>()), override);

C++ 预处理器在解析具有多个参数的模板时可能会出现问题std::string, int。如果发生这种情况,将返回类型移动到 typedef 会有所帮助。https://stackoverflow.com/a/38030161/2601293

typedef std::unordered_map<std::string, int> My_Type;
...
MAKE_MOCK0(my_function, (My_Type()), override);
于 2021-01-20T14:21:15.443 回答